Heim  >  Artikel  >  Web-Frontend  >  JSONP 跨域访问代理API-yahooapis实现代码_jquery

JSONP 跨域访问代理API-yahooapis实现代码_jquery

WBOY
WBOYOriginal
2016-05-16 17:47:411338Durchsuche

你是否遇到了想利用AJAX访问一些公网API,但是你又不想建立自己的代理服务,因为有时我根本就没打算涉及服务端任何代码,但是讨厌的浏览器的同源策略,阻止了我们的ajax调用。
比如我想访问一个天气的restfull api,如果我直接去GET:

复制代码 代码如下:

$.get("http://m.weather.com.cn/data/101010100.html");

 
看见这问题相信大家都不会陌生,也会很自然的得到解决方案,但是我这里真的不想touch任何服务端代码,用jsonp吧,但是服务端没实现契约。
在这里我是时候引入主角yahoo提供的jsonp代理:http://query.yahooapis.com/v1/public/yql
实现跨域访问代码为:http://jsfiddle.net/whitewolf/4UDpf/9/
html:
复制代码 代码如下:





复制代码 代码如下:

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);
}
});

});
效果:
 
多的就不用说了,jsonp原理我相信大家也很清楚。
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn