jQuery Ajax:获取特定对象值 [英] jQuery Ajax: get specific object value
问题描述
我正在使用 Ajax 访问字典 REST API.
$.ajax({url: "http://api.wordnik.com//v4/word.json/cat/definitions?api_key=mykey&includeRelated=false&includeTags=false&limit=1",数据类型:'json',成功:功能(数据){//成功时调用警报(数据.字);},错误:函数(e){//出现错误时调用console.log(e.message);}});
回复:
<预><代码>[{"textProns": [],"sourceDictionary": "ahd-legacy","exampleUses": [],相关词汇": [],标签": [],引文":[],"word": "猫","text": "一种小型食肉哺乳动物 (Felis catus 或 F.domesticus),很早就被驯化为捕鼠器和宠物,并存在于几个独特的品种和品种中.",序列":0",分数":0.0,"partOfSpeech": "名词","attributionText": "来自 The American Heritage® Dictionary of the English Language, 4th Edition"}]在我的测试示例中,我在成功时收到警报 undefined
.我看到的大多数 Ajax 示例都使用循环,但我返回了一个结果.如何从对象中提取 word
和 text
值?
如您所见,您的回复以 [
开头,以 ]
结尾.所以你的回应是一个数组.然后,在数组内部,您将获得对象(以 {
开头并以 }
结尾).所以你的 data
是一个数组,它可以用 data[x]
访问(x 是索引),并且所选对象的每个成员都可以用 .点符号:.word
、.text
等等.所以在你的情况下,如果只有一个结果,你可以做 data[0].word
.
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);
}
});
The response:
[
{
"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"
}
]
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?
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 Ajax:获取特定对象值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!