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);
}