JSONP跨域請求的示例分析

這篇文章主要介紹了JSONP跨域請求的示例分析,具有一定借鑒價值,需要的朋友可以參考下。希望大家閱讀完這篇文章后大有收獲。下面讓小編帶著大家一起了解一下。

創(chuàng)新互聯-專業(yè)網站定制、快速模板網站建設、高性價比西疇網站開發(fā)、企業(yè)建站全套包干低至880元,成熟完善的模板庫,直接使用。一站式西疇網站制作公司更省心,省錢,快速模板網站建設找我們,業(yè)務覆蓋西疇地區(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、前端編寫自己的函數,用script標簽發(fā)送get請求把函數名字帶上
2、服務器端接送到請求后獲取前端發(fā)送請求時的query,添加上自己的數據返回后。
3.、前端獲取返回的內容其實就自己的函數調用實參是數據對象。

  • 解釋的有點懵逼沒關系,用栗子說話。

前端代碼

<!doctype html>
<html lang="en">
<head>
    <title>Document</title>
</head>
<body>
<script>
    //編寫調用函數
    function getremotedata(data) {
        console.log(data);
    }
</script>
<!--用script標簽get方法把數據請求發(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ā)送的函數名稱,加上括號調用此函數,函數里加實參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數據,就實現了跨域請求啦。

感謝你能夠認真閱讀完這篇文章,希望小編分享JSONP跨域請求的示例分析內容對大家有幫助,同時也希望大家多多支持創(chuàng)新互聯,關注創(chuàng)新互聯行業(yè)資訊頻道,遇到問題就找創(chuàng)新互聯,詳細的解決方法等著你來學習!

新聞標題:JSONP跨域請求的示例分析
網頁鏈接:http://bm7419.com/article28/phdojp.html

成都網站建設公司_創(chuàng)新互聯,為您提供品牌網站設計、面包屑導航網站維護、軟件開發(fā)、全網營銷推廣、網站排名

廣告

聲明:本網站發(fā)布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創(chuàng)新互聯

網站托管運營