JSONP技術原理及實現


跨域問題一直是前端中常見的問題,每當說到跨域,第一浮現的技術必然就是JSONP

JSONP在我的理解,它並不是ajax,它是在文檔中插入一個script標簽,創建_callback方法,通過服務器配合執行_callback方法,並傳入一些參數

JSONP的局限就在於,因為是通過插入script標簽,所以參數只能通過url傳入,因此只能滿足get請求,特別jQuery的ajax方法時,即使設置type: 'POST',但是只要設置了dataType: 'jsonp',在請求時,都會自動使用GET請求

實現邏輯

step1: 創建_callback方法 (_callback中可以刪除script標簽和_callback方法)

step2: 插入script標簽

step3: 服務器輸出js

實現: 

var requestJsonp = function (opt) {
    var funName, script;

    /*
     * step1 創建_callback方法
     */ 

    //_callback函數名
    funName = '_cb' + (Math.random() * 1000000);
    //創建_callback方法
    window[funName] = function (data) {
        if (typeof opt.success == 'function') {
            opt.success(data);
        }

        
        window[funName] = null;
        delete window[funName];

        document.body.removeChild(script);
        script = null;
    };

    /*
     * step2 插入script標簽
     */
    script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = opt.url + (opt.url.indexOf('?') > -1 ? '&' : '?') + '_callback=' + funName;
    document.body.appendChild(script);

    /*
     * step3 服務器輸出js
     * 服務器應接受url參數中_callback的值,作為函數名執行輸出js
     * 類似輸出
     * _callback({"name":"jsonp","description":"jsonp test"});
     */ 

    /*
     * 處理error
     */
    script.addEventListener('error', function () {
        window[funName] = null;
        delete window[funName];

        if (typeof opt.error == 'function') {
            opt.error();
        }

        document.body.removeChild(script);
        script = null;
    });
};

requestJsonp({
    url: 'http://www.url.org?tid=Jsx2',
    success: function (data) {
        console.log(data);
    },
    error: function () {
        console.log('request error!');
    }
});

對於瀏覽器的行為就是插入script標簽,執行js代碼, 刪除script標簽

實現代碼並沒有考慮兼容以及傳入data后生成url的問題


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM