简体   繁体   English

从API抓取页面标题是否警报未定义?

[英]Grabbing title of page from an API is alerting undefined?

This bit of code below scans an API on Wikipedia, and then is supposed to alert the title of it by getting the JSON property "title". 下面的这段代码扫描了Wikipedia上的API,然后应该通过获取JSON属性“ title”来警告其标题。 However, it just alerts undefined , and for some reason, it alerts it twice. 但是,它只是警告undefined ,并且由于某种原因,它会两次警告它。 What am I doing wrong? 我究竟做错了什么?

$.get('https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro=&explaintext=&titles=Twitter', function(data){
  for (var Object in data){
    var Info = data[Object]
    var Title = Info["title"]
    alert(Title)
  }
})

This will work: 这将起作用:

$.get('https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro=&explaintext=&titles=Twitter', function(data) {
  $.each(data.query.pages, function( index, value ) {
    var title = value.title;
    alert(title);
  });
})

The query returns a data object, which has a query object within it, and one/multiple pages within that. 该查询返回一个data对象,该data对象中包含一个query对象,并在其中包含一个/多个pages Iterate over each page, and grab the title string. 遍历每个页面,并获取title字符串。

JSFiddle JSFiddle

Note: You may want to learn to use your browser's debugging tools, and read up on the JSON format. 注意:您可能想学习使用浏览器的调试工具,并阅读JSON格式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM