发起JSONP请求
发布时间:2020-12-16 18:57:45 所属栏目:百科 来源:网络整理
导读:JSONP说白了,就是利用 script 标签执行一个合法的跨域请求,然后执行自定义回调函数。代码如下: /** * 发起JSONP请求 * @function jsonp * @param {String} url 请求的URL * @param {Function} onSuccess jsonp响应成功后的回调函数*/function jsonp(url,o
JSONP说白了,就是利用 /** * 发起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); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |