jQuery的阿贾克斯:获取特定对象的值 [英] jQuery Ajax: get specific object value

查看:122
本文介绍了jQuery的阿贾克斯:获取特定对象的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm accessing a dictionary REST API using Ajax.

$.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"
  }
]

在我的测试示例中,我得到一个警告,未定义上的成功。大多数Ajax例子,我看到用循环但我返回一个结果。我怎样才能提取的对象文本值?

In my test example I get an alert undefined on success. Most Ajax examples I saw use loops but I'm returning one result. How can I extract the word and text values from the objects?

推荐答案

正如你可以看到你的反应开始 [结束] 。所以,你的反应是一个数组。然后,在数组中,你得到的对象(从 {结束} )。所以,你的数据是一个数组,它可以访问数据[X] (x是指数),以及所选对象的每个成员都可以使用.dot符号来访问: .word 的.text 等,所以在你的情况,如果有结果只有一个,你可以做数据[0] .word

As you can see your response starts with [ and ends with ]. So your response is an array. Then, inside the array, you get objects (starting with { and ending with }). So your data is an array, which can be accessed with data[x] (x being the index), and each member of the selected object can be accessed with the .dot notation: .word, .text etc. So in your case, if there's only one result, you can do data[0].word.

这篇关于jQuery的阿贾克斯:获取特定对象的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆