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