Have you ever encountered the situation where you want to use AJAX to access some public APIs, but you don’t want to build your own proxy service? Because sometimes I don’t intend to involve any code on the server side at all, but the annoying browser’s same-origin policy prevents us from doing so. ajax call.
For example, if I want to access a weather restfull api, if I go directly to GET:
$.get("http://m.weather.com.cn/data/101010100.html");
See this question I believe everyone will be familiar with it and will find the solution naturally, but I really don’t want to touch any server-side code here. I will use jsonp, but the server-side does not implement the contract.
Here it is time for me to introduce the jsonp proxy provided by the protagonist yahoo: http://query.yahooapis.com/v1/public/yql
The code to implement cross-domain access is: http://jsfiddle.net/whitewolf /4UDpf/9/
html:
< script type="text/javascript" src="http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js">
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:
Multiple Needless to say, I believe everyone knows the principle of jsonp.