Ajax跨域 —— Jsonp

2017-12-01  本文已影响13人  heheheyuanqing

同源策略

JSONP(JSON with Padding)

是一种跨域请求方式

function jsonp(params) {
    var options = params || {};
    var ohead = document.getElementsByTagName("head")[0];
    var oscript = document.createElement("script");
    var url = params.url || "";
    var callback = ("jsonp_" + Math.random()).replace(".","");
    var json = callback;

    url = url +"?appkey="+options.appkey+"&zipcode="+options.zipcode+"&callback="+callback;

    //发送请求
    oscript.src = url;
    ohead.appendChild(oscript);

    //创建回调函数
    window[callback] = function (json) {
        ohead.removeChild(oscript);
        clearTimeout(oscript.timer);
        window[callback] = null;
        options.success&&options.success(json);
    };

    //设置超时
    if (options.time){
        oscript.timer = setTimeout(function () {
            window[callback]=null;
            ohead.removeChild(oscript);
            options.erro&&options.erro({
                message:"连接超时"
            })
        },options.time);
    }

}

调用:

 jsonp({
                url: "http://api.jisuapi.com/zipcode/query",
                appkey: "d06f93228c91fe10",
                zipcode: zipcode,
                time:10000,
                success:function (data) {
                    oresult.innerHTML = zipcode + "是"+data.result[0].province+"省"+data.result[0].city+"市"+data.result[0].town+"\n"+
                        data.result[0].address+"\n"+data.result[1].address+"\n"+data.result[2].address+"\n"+data.result[3].address+"\n"+data.result[4].address;
                },
                erro:function (err) {
                    alert(err.message);
                }
            });
上一篇下一篇

猜你喜欢

热点阅读