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.