當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
JSONP实现原理-简析
生活随笔
收集整理的這篇文章主要介紹了
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实现原理-简析的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【Mac】安装 tesserocr 遇到
- 下一篇: CSS3--2D3D的使用