JSONP 跨域访问代理API-yahooapis实现代码
比如我想访问一个天气的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:
<script type="text/javascript" src="http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js"></script>
<div id="content">
</div>
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原理我相信大家也很清楚。
您可能感兴趣的文章:
JSONP 跨域访问代理API-yahooapis实现代码
jquery下利用jsonp跨域访问实现方法
jQuery 跨域访问问题解决方法
jquery ajax中使用jsonp的限制解决方法
JQuery的Ajax跨域请求原理概述及实例
用jQuery与JSONP轻松解决跨域访问的问题
php中json的跨域实例分析
网站跨域的五种解决方式
AJAX的跨域与JSONP(为文章自动添加短址的功能)
jquery的ajax和getJson跨域获取json数据的实现方法