Home  >  Article  >  Web Front-end  >  JSONP cross-domain access proxy API-yahooapis implementation code_jquery

JSONP cross-domain access proxy API-yahooapis implementation code_jquery

WBOY
WBOYOriginal
2016-05-16 17:47:411337browse

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:

Copy the code The code is as follows:

$.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:
Copy code The code is as follows:

< script type="text/javascript" src="http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js">



Copy code The 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:

Multiple Needless to say, I believe everyone knows the principle of jsonp.
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn