我正在使用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示例都使用循环,但是我返回一个结果。如何从对象中提取word和text值?
undefined
word
text
如您所见,您的回应以开头,以[结束]。因此,您的响应是一个数组。然后,在数组内部获得对象(以开头{和结尾})。所以,你data是一个数组,其可与被访问data[x]:(x是指数),并且将所选对象的每个成员可以与.DOT符号来访问.word,.text你的情况等,所以,如果只有一个结果,就可以做data[0].word。
[
]
{
}
data
data[x]
.word
.text
data[0].word