jQuery Ajax:获取特定的对象值

我正在使用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值?

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

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

你想改变这样的成功函数,

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

我validation了正确的价值。

jQuery AJAX