2010-03-10 39 views
6

$.getJSON()文檔狀態:爲什麼jQuery不自動附加JSONP回調?

If the specified URL is on a remote server, the request is treated as JSONP instead. See the discussion of the jsonp data type in $.ajax() for more details.

$.ajax()文檔的jsonp數據類型國家(重點煤礦):

Loads in a JSON block using JSONP. Will add an extra "?callback=?" to the end of your URL to specify the callback.

如此看來,如果我叫$.getJSON()有跨網域網址,額外的「回調=?」參數應該自動添加。 (文檔的其他部分支持這種解釋。)

但是,我沒有看到這種行爲。如果我不添加「回調=?」明確地說,jQuery不正確地生成一個XMLHttpRequest(由於我無法讀取跨域響應,所以它返回空數據)。如果我確實明確地添加它,jQuery正確地發出<腳本>請求。

下面是一個例子:

var URL = "http://www.geonames.org/postalCodeLookupJSON" + 
    "?postalcode=10504&country=US"; 

function alertResponse(data, status) { 
    alert("data: " + data + ", status: " + status); 
} 

$.getJSON(URL, alertResponse); 
// alerts "data: null, status: success" 

$.getJSON(URL + "&callback=?", alertResponse); 
// alerts "data: [object Object], status: undefined" 

那麼這是怎麼回事?我誤解了文檔還是忘記了一些東西?

不言而喻,這不是一個大問題,但我創建了一個web API,並且我特意將回調參數設置爲「回調」,希望能夠很好地適應jQuery的使用。

謝謝!

(編輯:我cross-posted this在jQuery的論壇,如果你有興趣)

回答

7

試試這個:

var URL = "http://www.geonames.org/postalCodeLookupJSON" + 
    "?postalcode=10504&country=US"; 
function alertResponse(data, status) { 
    alert("data: " + data + ", status: " + status); 
} 
$.ajax({ 
    url: URL, 
    dataType: 'jsonp', 
    jsonpCallback: 'alertResponse', 
}); 
+1

在你的例子中,你實際上是指'jsonpCallback:'alertResponse'',是的,那麼我就不需要明確地添加「callback =?」參數。但是這比'$ .getJSON()'的優雅更加冗長。它會很好,如果$ .getJSON()工作記錄... – 2010-03-12 07:53:31

3

是的,我想你誤會了。如文檔所述,$.getJSON$.ajax({datatype: 'json'....的快捷方式。除非添加callback=?參數,否則它永遠不會產生JSONP調用。

+0

嗯...我真的誤解了嗎?我引用的句子非常明確:「如果指定的URL位於遠程服務器上,請將該請求視爲JSONP。」 – 2010-03-12 07:48:28

+0

你是對的。這很混亂。 – 2010-03-12 20:53:24

0

我使用下面的代碼,

$阿賈克斯({ 網址:網址, 數據類型: 'JSONP', 成功:功能(數據) {// 做一些 } 錯誤:函數(jqXHR,textStatus,errorThrown){}, jsonpCallback:'login_callback', });

但是,回調有時會附加在URL的末尾,有時不在IE中。 雖然它在鉻和FF工作正常。