使用 AJAX (XMLHttpRequest) 查询 Wikipedia 的 API
我正在尝试使用 AJAX (XMLHttpRequest) 实现对维基百科 API 的简单请求.如果我在 Firefox 的地址栏中键入 url,我会得到一个整洁的 XML,那里不费吹灰之力.然而,调用完全相同的网址:
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);
返回一个空响应.根据 FireBug,我得到 200 OK 响应,但内容是空的.
returns an empty response. According to FireBug, I get a 200 OK response, but the content is just empty.
我怀疑我可能在 GET http 请求的标头上遗漏了某些内容.
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
但是您必须构建 jsonp 处理程序(或者您可以使用您喜欢的库来执行此操作),从您选择的 xml 切换到 json 输出格式并创建回调函数来解析结果并执行您的操作需要在页面上.
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.
相关文章