Using JSONP to achieve cross-domain access to data instances

Source: Internet
Author: User
Tags script tag

JS part

(Function (window, document) {
' Use strict ';
Varjsonp =function (URL, data, callback) {
1. Mount callback function
Varfnsuffix = Math.random (). toString (). replace ('. ', ');
Varcbfuncname = ' MY_JSON_CB ' + fnsuffix;
Window[cbfuncname] = callback;
2, the form of converting data into a URL string
{id=1,count=4}==>id=1&count=4
varquerystring = Url.indexof ('? ') = = 1? '? ': ' & '; Determine if there is a last in the URL? , no then?
for (Varkeyindata) {
QueryString + = key + ' = ' + Data[key] + ' & ';
}
3, processing URL in the callback function Url+=callback=sdgade
QueryString + = ' callback= ' + cbfuncname;
Querystring=?id=1&count=4&callback=sdgade
4. Create a SCRIPT tag
Varscriptelement = document.createelement (' script ');
SCRIPTELEMENT.SRC = URL + querystring;
5, put the script tag on the page
Document.body.appendChild (scriptelement);
};
window. $jsonp = JSONP;
}) (window, document)

Testing in the page

<! DOCTYPE html>
<title>jsonp</title>
<body>
<div id= "Htt" ></div>
<script type= "Text/javascript" src= "Http.js" ></script>
<script>
(function () {
$jsonp (' Http://api.douban.com/v2/movie/in_theaters ', {},
function (data) {
document.getElementById (' htt '). innerhtml=json.stringify (data);
});
})()
</script>
</body>

Results can return the results, the page is displayed as, indicating success!

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.