這篇文章主要介紹了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、前端編寫自己的函數,用script標簽發送get請求把函數名字帶上
2、服務器端接送到請求后獲取前端發送請求時的query,添加上自己的數據返回后。
3.、前端獲取返回的內容其實就自己的函數調用實參是數據對象。
解釋的有點懵逼沒關系,用栗子說話。
前端代碼
<!doctype html> <html lang="en"> <head> <title>Document</title> </head> <body> <script> //編寫調用函數 function getremotedata(data) { console.log(data); } </script> <!--用script標簽get方法把數據請求發送到后端--> <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的請求得到前端發送的函數名稱,加上括號調用此函數,函數里加實參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') })
這樣前端發送請求,無論回調是什么,后端都會返回回調加data數據,就實現了跨域請求啦。
感謝你能夠認真閱讀完這篇文章,希望小編分享JSONP跨域請求的示例分析內容對大家有幫助,同時也希望大家多多支持創新互聯建站,關注創新互聯網站制作公司行業資訊頻道,遇到問題就找創新互聯建站,詳細的解決方法等著你來學習!
當前題目:JSONP跨域請求的示例分析-創新互聯
本文路徑:http://m.kartarina.com/article28/ccggjp.html
成都網站建設公司_創新互聯,為您提供軟件開發、搜索引擎優化、網站制作、網站營銷、微信公眾號、App開發
聲明:本網站發布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創新互聯