侧边栏壁纸
博主头像
落叶人生博主等级

走进秋风,寻找秋天的落叶

  • 累计撰写 130562 篇文章
  • 累计创建 28 个标签
  • 累计收到 9 条评论
标签搜索

目 录CONTENT

文章目录

发起JSONP请求

2024-05-12 星期日 / 0 评论 / 0 点赞 / 83 阅读 / 1186 字

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

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

广告 广告

评论区