問題描述
我正在嘗試使用 AJAX (XMLHttpRequest) 實現(xiàn)對維基百科 API 的簡單請求.如果我在 Firefox 的地址欄中鍵入 url,我會得到一個整潔的 XML,那里不費吹灰之力.然而,調(diào)用完全相同的網(wǎng)址:
I am trying to implement a simple request to Wikipedia's API using AJAX (XMLHttpRequest). If I type the url in the address bar of Firefox, I get a neat XML, no sweat there. Yet, calling the exact same url with:
// this is my XMLHttpRequest object
httpObjectMain.open("GET", "http://en.wikipedia.org/w/api.php?action=query&format=xml&prop=langlinks&lllimit=500&titles=kaas", true);
httpObjectMain.send(null);
返回一個空響應(yīng).根據(jù) FireBug,我得到 200 OK 響應(yīng),但內(nèi)容是空的.
returns an empty response. According to FireBug, I get a 200 OK response, but the content is just empty.
我懷疑我可能在 GET http 請求的標(biāo)頭上遺漏了某些內(nèi)容.
I suspect I might be missing something on the header of the GET http request.
幫助!(謝謝!)
推薦答案
維基百科 API 確實支持 JSONP.你的查詢字符串會變成這樣:
The Wikipedia API does support JSONP. Your query string'll become something like this:
http://en.wikipedia.org/w/api.php?action=query&format=json&callback=test&prop=langlinks&lllimit=500&titles=kaas
但是您必須構(gòu)建 jsonp 處理程序(或者您可以使用您喜歡的庫來執(zhí)行此操作),從您選擇的 xml 切換到 json 輸出格式并創(chuàng)建回調(diào)函數(shù)來解析結(jié)果并執(zhí)行您的操作需要在頁面上.
But you'll have to build the jsonp handler (or you can use your favorite library to do it), switch to json output format from the xml you choose and create the callback function to parse the result and do the stuff you need on the page.
這篇關(guān)于使用 AJAX (XMLHttpRequest) 查詢 Wikipedia 的 API的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!