var jsonp = function() {
  var extend = function(obj, attrs) {
    for (var name in attrs) {
      obj[name] = attrs[name];
    }
  };
  var jsonp = function() {
    jsonp_imp.apply(null, arguments);
  };
  extend(jsonp, {
    guid: 0,
    requests: {},
    avail_tag: [],
    request_timeout: 5 //seconds
  });
  
  var Request = function(obj) {
    extend(this, obj);
    this.init && this.init();
  };
  var oo = Request.prototype;
  oo.remove = function() {
    var js = this.js;
    js.parentNode.removeChild(js);
    js = null;
    delete jsonp.requests[this.id];
  };
  oo.on_complete = function() {
    if (this.success) {
      this.success();
      this.success = null;
    }
  };
  oo.on_timeout = function() {
    var state = this.js.readyState;
    if (state != 'complete' && state != 'loaded' && this.failed) {
      this.failed();
      this.failed = null;
    }
    state = null;
    this.remove();
  };
  oo.init = function() {
    var request = this;
    this.js.onload = function() {
      request.on_complete();
    };
    setTimeout(function() {
      request.on_timeout();
    }, request.timeout);
  };
  
  var jsonp_imp = function(url, charset, timeout, failed, success) {
    var head = document.getElementsByTagName('head')[0];
    var js = document.createElement('script');
    head.appendChild(js);
    if (!charset) {
      charset = 'utf-8';
    }
    var id = jsonp.guid++;
    if (!timeout) {
      timeout = jsonp.request_timeout * 1000;
    }
    var now = new Date();
    var request = new Request({
      id: id,
      url: url,
      charset: charset,
      failed: failed,
      success: success,
      js: js,
      stat_time: now,
      timeout: timeout
    });
    
    
    jsonp.requests[id] = request;
    js.charset = charset;
    js.src = url;
    return id;
  };
  return jsonp;
}();

var url = "http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.js";
var url2 = "http://saic-sis.escdn.com/api.php?op=get_linkage_xjw&parentid=10000000000004&act=ajax_getlist&keyid=1&callback=cb";
jsonp(url2 ,
  null, 
  5000,
  function(){alert("failed");},  
  function(){alert("load ok");}
);
function cb(d) {
  console.log(d);
}

erichooooow
229 声望5 粉丝

simple is not easy