recherche

Maison  >  Questions et réponses  >  le corps du texte

javascript - Native JS encapsule la fonction JSONP

Comment puis-je écrire la fonction qui renvoie success : success dans ses paramètres ?

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错误

滿天的星座滿天的星座2706 Il y a quelques jours987

répondre à tous(1)je répondrai

  • ringa_lee

    ringa_lee2017-07-05 11:08:09

    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
    }

    répondre
    0
  • Annulerrépondre