自封装Jsonp完美解决冲突

// 完美解决并发冲突

  var Jsonp = {
    setJsonp: function(option) {
      var succenn_name = "g_" + new Date().getTime() + Math.floor(Math.random() * 8999 + 1000);
      var html = document.getElementsByTagName('html')[0];
      var scriptDOM = document.createElement('script');
      scriptDOM.type = "text/javascript";
      console.log(option.url + (option.url.indexOf('?') != -1 ? '&' : '?') + "jsoncallback=Jsonp." + succenn_name);
      scriptDOM.setAttribute('src', encodeURI(option.url + (option.url.indexOf('?') != -1 ? '&' : '?') + "jsoncallback=Jsonp." + succenn_name));

      html.appendChild(scriptDOM);
      html.removeChild(scriptDOM);

      this[succenn_name] = function(res) {
        this.func(res)
        delete this.that[this.name]
      }.bind({
        that: this,
        name: succenn_name,
        func: option.success
      });
    }
  }
  
  // 调用
  Jsonp.setJsonp({
    url: 'url',
    success: function(res) {

    }
  });

你可能感兴趣的:(Web前端)