首页 > 代码库 > jsonp跨域

jsonp跨域

var getJSONP = function ( url, callback ) {

  if( !url ) {

    return ;

  }

  var cbnum = ‘cb‘ + JSONP.counter++;

  var cbname = ‘JSONP.‘ + cbnum;

  if( url.indexOf(‘?‘) === -1) {

    url += ‘?jsonp=‘ + cbname;

  }else{

    url += ‘&jsonp=‘ + cbname;

  }

  

  JSONP[cbnum]= function ( res ) {

    try {

      callback( res );

    }catch( e ) {

      //

     }finally{

      delete getJSONP[cbnum];

      oScript.parentNode.removeChild(oScript);

    }

  };

  var oScript = document.createElement(‘script‘);

  oScript.src = http://www.mamicode.com/url;

  document.getElementsByTagName(‘head‘)[0].appendChild(oScript);

};

//调用

 JSONP.counter = 0;

getJSONP(‘http://i.cnblogs.com/EditPosts.aspx?opt=1‘, function () {});