Home  >  Article  >  Web Front-end  >  Solution to implement jQuery's $.getJSON using native JavaScript_jquery

Solution to implement jQuery's $.getJSON using native JavaScript_jquery

WBOY
WBOYOriginal
2016-05-16 17:34:48964browse

Today I am writing a DEMO, which uses jQuery’s $.getJSON method. After writing it, I found that this is the only place in jQuery that is used in the entire DEMO, but it is not cost-effective to introduce a jQuery, so I implemented it myself. A simple version, which can basically meet the needs, is now shared:

Copy the code The code is as follows:

var $ = {
getJSON: function(url, params, callbackFuncName, callback){
var paramsUrl ="",
jsonp = this.getQueryString(url)[callbackFuncName];
for (VAR Key in Params) {
Paramsurl = "&" Key "=" EncodeuricomPonent (Params [Key]);
}
URL = Paramsurl; Data) {
                window[jsonp] = undefined;
if (head) {
head.removeChild(script);
}
callback(data); };


var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.charset = "UTF-8";
script .src = url;

head.appendChild(script);

return true;
},
getQueryString: function(url) {
var result = {}, queryString = (url && url.indexOf("?")!=-1 && url.split("?")[1]) || location.search.substring(1),
      re = /([^&=] )= ([^&]*)/g, m;
while (m = re.exec(queryString)) {
result[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
}
}
}
};


Call DEMO as follows:



Copy code
The code is as follows:var url = "http://xxx.xxx.xxx?callback=jsonp123";var params = { a: 1,
b:2
};
$.getJSON(url, params, "callback", function(data){
//todo
});



Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn