介紹一個JSONP 跨域訪問代理API-yahooapis

 

你是否遇到了想利用AJAX訪問一些公網API,可是你又不想創建本身的代理服務,由於有時我根本就沒打算涉及服務端任何代碼,可是討厭的瀏覽器的三原策略,阻止了咱們的ajax調用。javascript

好比我想訪問一個天氣的restfull api,若是我直接去GEThtml

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

 

    看見這問題相信你們都不會陌生,也會很天然的獲得解決方案,可是我這裏真的不想touch任何服務端代碼,用jsonp吧,可是服務端沒實現契約。ajax

在這裏我是時候引入主角yahoo提供的jsonp代理:http://query.yahooapis.com/v1/public/yqljson

實現跨域訪問代碼爲:http://jsfiddle.net/whitewolf/4UDpf/9/api

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

});瀏覽器

效果:restful

 

      多的就不用說了,jsonp原理我相信你們也很清楚。 ide

相關文章
相關標籤/搜索