Use native JavaScript to implement jQuery's $. getJSON Solution

Source: Internet
Author: User

I am writing a DEMO today, where $. after the getJSON method is completed, it is found that jQuery is used in the entire DEMO, but it is not cost-effective to introduce a jQuery method. Therefore, a simple version is implemented by yourself, the basic requirements can be met:
Copy codeThe 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;
Window [jsonp] = function (data ){
Window [jsonp] = undefined;
Try {
Delete window [jsonp];
} Catch (e ){}

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.exe c (queryString )){
Result [decodeURIComponent (m [1])] = decodeURIComponent (m [2]);
}
Return result;
}
};

The DEMO is called as follows:
Copy codeThe 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
});

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.