How to make a JSONP request from Javascript without JQuery?

后端 未结 12 1425
遇见更好的自我
遇见更好的自我 2020-11-22 17:27

Can I make a cross-domain JSONP request in JavaScript without using jQuery or other external library? I would like to use JavaScript itself and then parse the data and make

12条回答
  •  深忆病人
    2020-11-22 17:37

    the way I use jsonp like below:

    function jsonp(uri) {
        return new Promise(function(resolve, reject) {
            var id = '_' + Math.round(10000 * Math.random());
            var callbackName = 'jsonp_callback_' + id;
            window[callbackName] = function(data) {
                delete window[callbackName];
                var ele = document.getElementById(id);
                ele.parentNode.removeChild(ele);
                resolve(data);
            }
    
            var src = uri + '&callback=' + callbackName;
            var script = document.createElement('script');
            script.src = src;
            script.id = id;
            script.addEventListener('error', reject);
            (document.getElementsByTagName('head')[0] || document.body || document.documentElement).appendChild(script)
        });
    }
    

    then use 'jsonp' method like this:

    jsonp('http://xxx/cors').then(function(data){
        console.log(data);
    });
    

    reference:

    JavaScript XMLHttpRequest using JsonP

    http://www.w3ctech.com/topic/721 (talk about the way of use Promise)

提交回复
热议问题