parse json string from wikimedia using jquery

社会主义新天地 提交于 2019-11-29 12:13:02

If you want the actual html as it is displayed in the wikipage, use action=parse instead. And yes, the result objects are deeply nested. But no reason to loop over them!

  • the first property is always the action, here: query
  • you have requested properties of pages, so you will receive pages
  • which are keyed by their page id. This is the only step to use a loop
  • Each page object has certain properties (like a title), you're interested in the revisions
  • this is an array of revision objects, you need the only and first
  • the sourcetext property of a revision object is the *

So, just do it:

if (data && data.query && data.query.pages)
    var pages = data.query.pages;
else
    // error: No pages returned / other problems!
for (var id in pages) { // in your case a loop over one property
    if (pages[id].revisions && pages[id].revisions[0] && pages[id].revisions[0]["*"])
        var content = pages[id].revisions[0]["*"];
    else
        // error: No revision content returned for whatever reasons!
}
// use "content" variable here

Dont forget to check for the existance of each object! If you requested no pages, there will be no pages object; this is only the case when the pages "array" is empty. A page may be missing/invalid title or something else, so that is has no revisions. etc.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!