发起JSONP请求

原创
2016/05/23 15:17
阅读数 246

JSONP说白了,就是利用<script>标签执行一个合法的跨域请求,然后执行自定义回调函数。代码如下:

/**
 * 发起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);
}
展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
0 评论
0 收藏
2
分享
返回顶部
顶部