javascript - Native js encapsulates jsonp function
滿天的星座
滿天的星座 2017-07-05 11:06:09
0
1
979

How can we make the function that returns success: success written inside its parameters?

function success(data){
    console.log(data);
}
jsonp({
    url:'https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su',
    type:'get',
    data:{
        wd:'jsonp'
    },
    callback :'cb',
    success:success
});
function jsonp(options){
    var url = options.url;
    var data = options.data;

    format(data,options,function(str,callback){
        var oBody = document.getElementsByTagName('body')[0];
        var oScript = document.createElement('script');
        oScript.setAttribute('src',url+'?'+str + options.callback+'='+callback);
        oBody.appendChild(oScript);
    });
    return options.success;

};
function format(data,options,callback){
    var callbackName = '';
    var str = '';
    for(var p in data){//格式化get提交的参数
        str += p+'='+data[p]+'&';
    }
    for(var p in options){
        if(options[p] == options.success){//取出要返回的函数名
            callbackName = p;
            callback && callback(str,callbackName);
        }
    }
}

如果是这么写success:function(data){conosle.log(data);}

会报一个success is undefined错误

滿天的星座
滿天的星座

reply all(1)
ringa_lee

https://jsfiddle.net/hsfzxjy/...

jsonp({
    url: 'https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su',
    type: 'get',
    data:{
        wd: 'jsonp'
    },
    callback: 'cb',
    success: function (data) { console.log(data) }
});

function jsonp (options) {
    let url = options.url
    let data = options.data
    
    let oBody = document.getElementsByTagName('body')[0]
    let oScript = document.createElement('script')
    
    let callbackName = 'cb' + (~~(Math.random()*0xffffff)).toString(16)
    window[callbackName] = function (result) {
        options.success(result)        
    }
    data[options.callback] = callbackName
    
    oScript
        .setAttribute('src', url + '?' + format(data))
    oBody.append(oScript)
}
function format(data) {
    let str = ''
    for (var p in data) {
        str += encodeURIComponent(p) + '=' + encodeURIComponent(data[p]) + '&'
    }
    return str
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template