native JSONP specifically implemented
First on the code:
//http://www.baidu.com?aa=11&callback=my_jsonp04349289664328899 varJSONP =function(url,param,callback) {//process URL address, find? , if not? This variable has a "?", is there? This variable receives a & varQueryString = Url.indexof ("?") = =-1? "?": "&"; //processing parameter {xx:xx} for(varKinchparam) {QueryString+ = k + "=" + Param[k] + ' & ';//? K=para[k] } //Handling callback function names varRandom = Math.random (). toString (). Replace (".", ""); varCbval = "My_jsonp" +Random; varCB = "callback=" +Cbval; QueryString+=CB; varScript = document.createelement ("Script"); SCRIPT.SRC= URL +querystring; //attach the name of the callback function to the windowWindow[cbval] =function(param) {//This is where the callback is performed and the callback is used to process the argumentscallback (param); //Delete this script when you get it.document.body.removeChild (script); }; Document.body.appendChild (script); } JSONP ("Https://www.baidu.com", {aa:11}, function() {console.log (param); } );
Ideas:
Abstract the string to be processed first
After processing the URL, create a new script tag to attach to the page
Hang the handled callback function on the Window object
Erase the script after the callback.
steps:
Take a random address, like Baidu.
var function (Url,para,callback) {}
Address, parameter, callback
Start processing URL Address
var queryString = Url.indexof ("?") = =-1? "?": "&"; // look at the URL there is no?, if there is a description as long as the parameters are good, no words querystring default is? // there are usually several parameters to the address, so the data format is an object, such as {aa:11} for (var in para) { + = k + ' = ' + para[k] + ' & '; // ?aa=11&}
Handling Callback Functions
The idea of imitating JQ, the function name is random, avoid and the page of a function duplicate
Requires a random non-floating-point number
Name of parameter
var random = Math.random (). toString (). Replace (".", ""); // random non-floating-point number var cbvalue = "JP" + random; // You cannot do a function name with the beginning of a number var cb = "callback=" + cbvalue; // callback = jp016548432158485queryString + = CB; // placed behind the processing URL string
Create a script
var script = document.createelement ("script"= querystring;document.body.appendchild (script);
Mount the callback function on the page and pass the parameter
function (para) { callback (para); // take out the parameters and delete them, ladder. document.body.removeChild (script);}
Complete, try Calling
Jsonp ("www.jd.com", {num:10},function() { console.log (para);})
Handwriting a Jsonp