這篇文章主要介紹了JSONP跨域請求的示例分析,具有一定借鑒價值,需要的朋友可以參考下。希望大家閱讀完這篇文章后大有收獲。下面讓小編帶著大家一起了解一下。
維基百科的解釋:
JSONP (JSON with Padding or JSON-P[1]) is a javascript pattern to request data by loading a <script> tag. It was proposed by Bob Ippolito in 2005.[2] JSONP enables sharing of data bypassing same-origin policy. The policy disallows running JavaScript to read media DOM elements or XHR data fetched from outside the page's origin. The aggregation of the site's scheme, port number and host name identifies as its origin.
我的理解是:
1、前端編寫自己的函數(shù),用script標簽發(fā)送get請求把函數(shù)名字帶上
2、服務器端接送到請求后獲取前端發(fā)送請求時的query,添加上自己的數(shù)據(jù)返回后。
3.、前端獲取返回的內(nèi)容其實就自己的函數(shù)調用實參是數(shù)據(jù)對象。
解釋的有點懵逼沒關系,用栗子說話。
前端代碼
<!doctype html> <html lang="en"> <head> <title>Document</title> </head> <body> <script> //編寫調用函數(shù) function getremotedata(data) { console.log(data); } </script> <!--用script標簽get方法把數(shù)據(jù)請求發(fā)送到后端--> <script src="http://localhost:3999/?callback=getremotedata"></script> </body> </html>
后端代碼
//用node編寫一個簡單的服務器 const http = require('http'); const urlModule = require('url'); const server = http.createServer(); server.on('request', function (req, res) { //urlModule.parse(req.url.url)的請求 就是這個對象 // { // protocol: null, // slashes: null, // auth: null, // host: null, // port: null, // hostname: null, // hash: null, // search: '?callback=getremotedata', // query: 'callback=getremotedata', // pathname: '/', // path: '/?callback=getremotedata', // href: '/?callback=getremotedata' } // 對象結構賦值得到query是一個對象 const {pathname: url, query} = urlModule.parse(req.url, true) if (url === '/') { var data = { name: '大毛', age: 18, gender: '未知' }; // 解析query的請求得到前端發(fā)送的函數(shù)名稱,加上括號調用此函數(shù),函數(shù)里加實參servedata返回 var scripteStr = `${query.callback}(${JSON.stringify(data)})` console.log(scripteStr) res.end(scripteStr) } else { res.end('404') } }); server.listen('3999', function () { console.log('server is running 3999') })
這樣前端發(fā)送請求,無論回調是什么,后端都會返回回調加data數(shù)據(jù),就實現(xiàn)了跨域請求啦。
感謝你能夠認真閱讀完這篇文章,希望小編分享JSONP跨域請求的示例分析內(nèi)容對大家有幫助,同時也希望大家多多支持創(chuàng)新互聯(lián)建站,關注創(chuàng)新互聯(lián)網(wǎng)站制作公司行業(yè)資訊頻道,遇到問題就找創(chuàng)新互聯(lián)建站,詳細的解決方法等著你來學習!
當前題目:JSONP跨域請求的示例分析-創(chuàng)新互聯(lián)
本文路徑:http://aaarwkj.com/article28/ccggjp.html
成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供軟件開發(fā)、搜索引擎優(yōu)化、網(wǎng)站制作、網(wǎng)站營銷、微信公眾號、App開發(fā)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉載內(nèi)容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉載,或轉載時需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容