網上收集修改的原生jsonp代碼

來源:互聯網
上載者:User

標籤:http   io   ar   os   sp   java   for   on   art   

;(function(){    var formatParams = function(data) {//格式化參數        var arr = [];        for (var name in data) {            arr.push(encodeURIComponent(name) + ‘=‘ + encodeURIComponent(data[name]));        }        return arr.join(‘&‘);    }    var jsonp = function(options) {        options = options || {};        if (!options.url || !options.callback) {            throw new Error("參數不合法");        }        //建立 script 標籤並加入到頁面中        var callbackName = (‘jsonp_‘ + Math.random()).replace(".", "");        var oHead = document.getElementsByTagName(‘head‘)[0];        var params = "";        if(options.data){            options.data[options.callback] = callbackName;            params += formatParams(options.data);        }else{            params+=options.callback+"="+callbackName;        }        var oS = document.createElement(‘script‘);        oHead.appendChild(oS);        //建立jsonp回呼函數        window[callbackName] = function (json) {            oHead.removeChild(oS);            clearTimeout(oS.timer);            window[callbackName] = null;            options.success && options.success(json);        };        //發送請求        oS.src = options.url + ‘?‘ + params;        //逾時處理        if (options.time) {            oS.timer = setTimeout(function () {                window[callbackName] = null;                oHead.removeChild(oS);                options.fail && options.fail({ message: "逾時" });            }, options.time);        }    };    window.jsonp = jsonp;})();//調用方法/*jsonp({    url:"http://www.baidu.com",    callback:"callback",   //跟後台協商的接收回調名    data:{id:"1000120"},    success:function(json){        alert("jsonp_ok");    },    fail:function(){        alert("fail");    },    time:10000})*/

原文連結:http://www.html-js.com/article/JavaScript-based-implementation-of-AJAX-JSONP-and-native-JS-DOM-finishes-loading-events

網上收集修改的原生jsonp代碼

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.