Do you have a problem with using AJAX to access some public-network APIs, but you don't want to set up your own proxy service, because sometimes I'm not going to involve any of the server's code, but the annoying browser's homology strategy blocks our Ajax calls.
For example I would like to visit a weather Restfull API if I go straight to get:
Copy Code code as follows:
$.get ("http://m.weather.com.cn/data/101010100.html");
See this problem believe that everyone will not be unfamiliar, will naturally get the solution, but I really do not want to touch any service-side code, with Jsonp bar, but the server did not implement the contract.
It's time for me to introduce the main character Yahoo provides JSONP agent: HTTP://QUERY.YAHOOAPIS.COM/V1/PUBLIC/YQL
Implementing Cross-domain Access code is: http://jsfiddle.net/whitewolf/4UDpf/9/
Html:
Copy Code code as follows:
<script type= "Text/javascript" src= "Http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js" ></script >
<div id= "Content" >
</div>
Copy Code code 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:
Much needless to say, the principle of jsonp I believe that we are also very clear.