發起JSONP請求

JSONP說白了,就是利用<script>標籤執行一個合法的跨域請求,而後執行自定義回調函數。代碼以下:json

/**
 * 發起JSONP請求
 * @function jsonp
 * @param {String} url 請求的URL
 * @param {Function} onSuccess jsonp響應成功後的回調函數
*/
function jsonp(url, onSuccess) {
    var hash = Math.random().toString().slice(2);
    window['jsonp' + hash] = function(data) {
        if ('undefined' !== typeof data.errCode) {
            data.errCode = parseInt(data.errCode, 10);
        }
        clearJsonp(hash);
        onSuccess(data);
    };
    var script = document.createElement('script');
    script.id = 'js' + hash;
    script.onerror = function() {
        console.log('JSONP failed');
        clearJsonp(hash);
        onSuccess();
    };
    script.src = url + '&_=' + hash + '&jsonp=jsonp' + hash;
    document.body.appendChild(script);
}

// 清理jsonp臨時數據
function clearJsonp (hash) {
    window['jsonp' + hash] = null;
    delete window['jsonp' + hash];
    setTimeout(function(){
        document.body.removeChild(document.getElementById('js' + hash));
    }, 50);
}
相關文章
相關標籤/搜索