您的位置:首页 > Web前端 > JavaScript

发起JSONP请求

2016-05-23 00:00 393 查看
摘要: 自己写的一个jsonp实现

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);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  jsonp