1
我使用jQuery的Ajax調用來查詢返回純JSON數據跨域網址:是否有可能通過使用jQuery的跨域請求使JSONP請求獲取JSON數據?
function getAlibrisSuggestions(theKeywords)
{
$.ajax(
{
url: "http://www.alibris.com/cgi-bin/complete?site=18640838&mtype=B&term=" + encodeURI(theKeywords),
dataType: 'jsonp',
type: "GET",
crossDomain: true,
/* None of these helped obviously since the return is not JSONP but JSON
complete: onSuggestionsFetched,
beforeSend: onBeforeSend,
success: onSuccess,
dataFilter: onDataFilter,
*/
});
}
樣品網址:
http://www.alibris.com/cgi-bin/complete?site=18640838&mtype=B&term=book
JSON響應:
[
{"l": "BP", "v": "books llc"},
{"l": "BA", "v": "books time-life"},
{"l": "BA", "v": "books general"},
{"l": "BA", "v": "books sunset"},
{"l": "BP", "v": "books on demand"},
{"l": "BA", "v": "books golden"},
{"l": "BA", "v": "books scholastic"},
{"l": "BP", "v": "book jungle"},
{"l": "BA", "v": "books chronicle"},
{"l": "BP", "v": "booksurge publishing"}
]
由於它是跨域,我必須使用JSONP來避免原始錯誤。問題是,正如您從該URL的響應中看到的那樣,返回是純JSON。由於它未被格式化爲Javascript,因此它導致jQuery在Chrome控制檯中返回結果狀態「parsererror」和預期的「資源解釋爲腳本,但作爲MIME類型text/plain傳輸」警告。
我無法控制外部服務器。我想避免將調用包裝在服務器端腳本中,只是爲了將返回打扮成Javascript。有誰知道一個聰明的方式能夠處理退貨?
- roschler
我很害怕這個。我希望一些聰明的靈魂想出瞭如何在DOM注入時捕獲Javascript警告,或者將注入誤解爲對未引用的Javascript函數的調用並捕獲錯誤,這很奇怪。 –
我知道你可以利用的唯一漏洞在John Resig的帖子中有解釋:http://ejohn.org/blog/re-securing-json/。但是,該方法不適用於Firefox 3的發行版,因此對您而言可能無用。 –