這篇文章主要介紹了JSONP跨域請求的示例分析,具有一定借鑒價值,需要的朋友可以參考下。希望大家閱讀完這篇文章后大有收獲。下面讓小編帶著大家一起了解一下。
創(chuàng)新互聯(lián)-專業(yè)網(wǎng)站定制、快速模板網(wǎng)站建設(shè)、高性價比西疇網(wǎng)站開發(fā)、企業(yè)建站全套包干低至880元,成熟完善的模板庫,直接使用。一站式西疇網(wǎng)站制作公司更省心,省錢,快速模板網(wǎng)站建設(shè)找我們,業(yè)務(wù)覆蓋西疇地區(qū)。費用合理售后完善,十載實體公司更值得信賴。
維基百科的解釋:
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標(biāo)簽發(fā)送get請求把函數(shù)名字帶上
2、服務(wù)器端接送到請求后獲取前端發(fā)送請求時的query,添加上自己的數(shù)據(jù)返回后。
3.、前端獲取返回的內(nèi)容其實就自己的函數(shù)調(diào)用實參是數(shù)據(jù)對象。
解釋的有點懵逼沒關(guān)系,用栗子說話。
前端代碼
<!doctype html> <html lang="en"> <head> <title>Document</title> </head> <body> <script> //編寫調(diào)用函數(shù) function getremotedata(data) { console.log(data); } </script> <!--用script標(biāo)簽get方法把數(shù)據(jù)請求發(fā)送到后端--> <script src="http://localhost:3999/?callback=getremotedata"></script> </body> </html>
后端代碼
//用node編寫一個簡單的服務(wù)器 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' } // 對象結(jié)構(gòu)賦值得到query是一個對象 const {pathname: url, query} = urlModule.parse(req.url, true) if (url === '/') { var data = { name: '大毛', age: 18, gender: '未知' }; // 解析query的請求得到前端發(fā)送的函數(shù)名稱,加上括號調(diào)用此函數(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ā)送請求,無論回調(diào)是什么,后端都會返回回調(diào)加data數(shù)據(jù),就實現(xiàn)了跨域請求啦。
感謝你能夠認(rèn)真閱讀完這篇文章,希望小編分享JSONP跨域請求的示例分析內(nèi)容對大家有幫助,同時也希望大家多多支持創(chuàng)新互聯(lián),關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,遇到問題就找創(chuàng)新互聯(lián),詳細(xì)的解決方法等著你來學(xué)習(xí)!
新聞標(biāo)題:JSONP跨域請求的示例分析
網(wǎng)頁鏈接:http://m.newbst.com/article28/phdojp.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供品牌網(wǎng)站設(shè)計、面包屑導(dǎo)航、網(wǎng)站維護、軟件開發(fā)、全網(wǎng)營銷推廣、網(wǎng)站排名
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)