【问题标题】:jQuery Ajax: get specific object valuejQuery Ajax:获取特定对象值
【发布时间】:2012-07-20 19:26:42
【问题描述】:

我正在使用 Ajax 访问字典 REST API。

$.ajax({
  url: "http://api.wordnik.com//v4/word.json/cat/definitions?api_key=mykey&includeRelated=false&includeTags=false&limit=1",
  dataType : 'json',
  success: function(data) {
    //called when successful
    alert(data.word);
  },
  error: function(e) {
    //called when there is an error
    console.log(e.message);
  }
});

回应:

[
  {
    "textProns": [],
    "sourceDictionary": "ahd-legacy",
    "exampleUses": [],
    "relatedWords": [],
    "labels": [],
    "citations": [],
    "word": "cat",
    "text": "A small carnivorous mammal (Felis catus or F. domesticus) domesticated since early times as a catcher of rats and mice and as a pet and existing in several distinctive breeds and varieties.",
    "sequence": "0",
    "score": 0.0,
    "partOfSpeech": "noun",
    "attributionText": "from The American Heritage® Dictionary of the English Language, 4th Edition"
  }
]

在我的测试示例中,我在成功时收到警报 undefined。我看到的大多数 Ajax 示例都使用循环,但我返回一个结果。如何从对象中提取 wordtext 值?

【问题讨论】:

  • +1 给语法警察修改我的英语

标签: jquery ajax json api


【解决方案1】:

如您所见,您的回复以[ 开头,以] 结尾。所以你的回应是一个数组。然后,在数组内部,您将获得对象(以{ 开始,以} 结束)。所以你的data 是一个数组,可以使用data[x] 访问(x 是索引),并且可以使用.dot 表示法访问所选对象的每个成员:.word.text 等。所以在您的情况下,如果只有一个结果,您可以使用data[0].word

【讨论】:

  • 我得到输出“未定义”。可能是什么问题??
  • 我也得到输出“未定义”。
【解决方案2】:

响应是数组内的一个对象。试试data[0].word

【讨论】:

    【解决方案3】:

    你想像这样改变success函数,

    success: function(data) {
      alert(data[0].word);
    }
    

    我验证了正确的值。

    jQuery AJAX

    【讨论】:

      猜你喜欢
      • 2016-06-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-17
      • 2017-11-22
      • 1970-01-01
      • 2018-02-26
      • 1970-01-01
      相关资源
      最近更新 更多