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

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

  比如我想访问一个天气的restfull api,如果我直接去GET:

  

复制代码 代码如下:

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

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

  看见这问题相信大家都不会陌生,也会很自然的得到解决方案,但是我这里真的不想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 跨域访问代理API-yahooapis实现代码

  多的就不用说了,jsonp原理我相信大家也很清楚。