JSONP cross-origin access proxy API-yahooapis implementation code

Source: Internet
Author: User

Do you want to use AJAX to access some public network APIs, but you do not want to build your own proxy service, because sometimes I have no intention of involving any code on the server, however, the annoying browser's same-origin policy blocks ajax calls.
For example, if I want to access a weather restfull api, If I directly go to GET:
Copy codeThe Code is as follows:
$. Get ("http://m.weather.com.cn/data/101010100.html ");

 
I believe everyone will be familiar with this problem and will naturally get a solution. But I really don't want to touch any server code here. Use jsonp, but the server has not implemented the contract.
Here I am introducing the jsonp agent from the main character yahoo: http://query.yahooapis.com/v1/public/yql
Implementing cross-origin access code: http://jsfiddle.net/whitewolf/4UDpf/9/
Html:
Copy codeThe Code is as follows:
<Script type = "text/javascript" src = "http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js"> </script>
<Div id = "content">
</Div>

Copy codeThe Code is as follows:
Js:
$ (Function (){
$. GetJSON ("http://query.yahooapis.com/v1/public/yql ",{
Q: "select * from json where url = \" http://m.weather.com.cn/data/101010100.html \"",
Format: "json"
}, Function (data ){
Var $ content = $ ("# content ")
If (data. query. results ){
$ Content. text (JSON. stringify (data. query. results ));
} Else {
$ Content. text ('no such code: '+ code );
}
});

});
Effect:

Needless to say, I believe everyone knows the jsonp principle.

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.