日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

JSONP实现原理-简析

發布時間:2025/3/20 javascript 35 豆豆
生活随笔 收集整理的這篇文章主要介紹了 JSONP实现原理-简析 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

使用script標簽是如何實現跨域請求的,它是一個新技術,還是一個技巧? 下面我們來看看,其中簡單的原理:

我們寫一個很平常的example.js,文件內容展示如下:

getJson({results: [{name: 'xxx',code: 1}] }); 復制代碼

接下來,再寫一個簡單的index.html文件:

<!DOCTYPE html> <html><head><meta charset="utf-8" /><title>jsonp</title><script>function getJson(data) {console.log(data);}</script><script src="http://127.0.0.1:3000/example.js"></script></head><body></body> </html> 復制代碼

上面的index.html代碼,當成功的請求到example.js后,相當于這樣:

<!DOCTYPE html> <html><head><meta charset="utf-8" /><title>jsonp</title><script>function getJson(data) {console.log(data);}</script><script>// 這里是:src="http://127.0.0.1:3000/example.js"請求成功后,返回的代碼(數據)getJson({results: [{name: 'xxx',code: 1}]});</script></head><body></body> </html> 復制代碼

相信寫到這里,是能看得明白的,下面正式開始說JSONP的實現,我用的是nodejs后臺:

前端代碼index.html,給"http://http://127.0.0.1:3000/example.js"請求地址加一個get請求參數?callback=getJson,代碼示例如下:

<!DOCTYPE html> <html><head><meta charset="utf-8" /><title>jsonp</title><script>function getJson(data) {console.log(data);}</script><script src="http://127.0.0.1:3000/example.js?callback=getJson"></script></head><body></body> </html> 復制代碼

后端server.js代碼如下:

const express = require('express'); const server = express();server.use('/example.js', (req, res) => {// req.query.callback是getJsonlet methodName = req.query.callback; let data = {results: [{name: 'xxx',code: 1}]};let dataStr = JSON.stringify(data),// 相當于sendStr = `getJson(${dataStr})`sendStr = `${methodName}(${dataStr})`;res.send(sendStr); });server.listen(3000); console.log('server running at 127.0.0.1:3000'); 復制代碼

當請求成功后,index.html代碼解析如下:

<!DOCTYPE html> <html><head><meta charset="utf-8" /><title>jsonp</title><script>function getJson(data) {console.log(data);}</script><script>// 這里是:src="http://127.0.0.1:3000/example.js?callback=getJson"請求成功后,返回的代碼(數據)getJson('{"results":[{"name":"xxx","code":1}]}')</script></head><body></body> </html> 復制代碼

最后聲明,為了方便大家理解,我把請求寫成了一個example.js,其實接口只要一個字符串就可以了,例如"http://127.0.0.1:3000/example?callback=getJson",其中.js文件格式,完全是為了幫助大家理解。

轉載于:https://juejin.im/post/5c8c9393e51d452865236ad3

總結

以上是生活随笔為你收集整理的JSONP实现原理-简析的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。