2011-12-14 65 views
1

我想跨域使用jQuery getJSON方法拉數據。我已經安裝上JS FIDDLE這裏測試:getJSON不通過域拉動數據

http://jsfiddle.net/kbPV7/1/

我真的不知道爲什麼,這是行不通的。如果我在同一個域上上傳這個文件或者在本地使用feeTest.html,代碼就可以工作。

但是,如果我上傳或使用真正預期的網址,則Feed不起作用。

另外,如果我在同一個域中使用.ajax,它可以工作。但我的理解是,.ajax不能跨越不同的域,這就是.getJSON的用途。

感謝您的幫助!

+1

不,`.getJSON`用於從同一個域中檢索JSON數據。 jQuery會自動將數據解析爲JavaScript數據結構。如果你想進行跨域調用,你必須使用JSONP(你可以使用``。getJSON`),這必須由服務器支持。 – 2011-12-14 16:32:52

回答

0

.getJSON()是帶有預配置選項的.ajax()的簡寫。見documentation

URL中的數據爲JSON格式,不支持跨域。它們需要以JSONP格式返回,這意味着它們必須能夠將數據放入指定的回調函數中。

您必須修改服務以使用JSONP,並允許您指定回調參數或使用其他方式訪問服務。

使用YQL訪問您的數據的一個例子:

$.ajax({ 
    url: 'http://query.yahooapis.com/v1/public/yql', 
    data: { 
    q: 'select * from json where url="http://www.corporatereport.com/SampleSites/rockwellCollins/mockup5/feedTest.html"', 
    format: 'json' 
    }, 
    dataType: 'JSONP', 
    success: function(data) { 
    // this is the XML in JSON format 
    console.log(data.query.results.json.news); 

    // example - display list of titles 
    var titles = $.map(data.query.results.json.news, function(news) { 
     return '<li>' + news.t + '</li>'; 
    }); 
    $('<ul />', { html: titles.join('') }).appendTo('body'); 
    } 
}); 

HERE是代碼。

0

以下是您可以訪問兩個可以控制的不同域的情況,並且您必須進行跨域調用。所以,這種情況是無法避免的,而且您無法控制以JSONP格式返回數據。

var script = document.createElement('script'); 
script.type = "text/javascript";   
script.src='path to crossdomain source.js'; 
document.getElementsByTagName("head")[0].appendChild(script); 

lookupInterval = setInterval("function_to_call()", 1000); 

var lookupCounter=0; 

function function_to_call(){ 
    //give up after 5 times 
    if(++lookupCounter == 5) 
     return clearInterval(lookupInterval); 

    try{ 
     var cities = GEO_DATA_2011_11_28.cities.city; 

     //since we found our data, let's clean the interval call 
     return clearInterval(lookupInterval) 
    } 
    catch(e){ 
     //do nothing, we are actually controlling the situation with the if condition at the beginning 
    } 
} 

我們在遠程js文件中將數據定義爲var GEO_DATA_2011_11_28 = {}以JSON格式。這裏的訣竅是我們動態地將腳本文件注入到HTML的頭部。由於腳本塊可以毫無問題地加載跨域腳本,因此我們可以採用延遲的方式來完成。考慮到加載腳本可能會有延遲,我們正在調用一個函數來檢查我們想要獲取的數據。

這個解決方案很有必要,因爲沒有辦法用JSONP發送數據,所以我們依賴於閱讀簡單的js文件。