如何访问 JSON 对象名称/值? [英] How to access JSON Object name/value?
问题描述
function (data) {
//add values based on activity type
//data = JSON.parse(data);
//alert(abc.Phone1);
alert(data.myName)
alert(data.toString());
if (activityType == "Phone") {
}
return;
},
如你所见,$.ajax
的回调函数从控制器中获取 JSON
数据.
As you can see this callback function of $.ajax
taking JSON
data from controller.
例如:
[{"name":"myName","address":"myAddress" }]
在这种情况下,我的第一个警报给我未定义和第二/第三个警报弹出窗口:
In this case my first alert giving me undefined and second/third alert popup comes up with:
[{"name":"myName" ,"address": "myAddress" }]
如何按名称访问值,以便我的第一个警报用 myName
填充,这是 name
的值?
How can I access value by name so that my first alert filled out with myName
which is value of name
?
推荐答案
除了解析 JSON,您还可以执行以下操作:
In stead of parsing JSON you can do like followng:
$.ajax({
..
dataType: 'json' // using json, jquery will make parse for you
});
要访问 JSON 的属性,请执行以下操作:
To access a property of your JSON do following:
data[0].name;
data[0].address;
为什么你需要 data[0]
因为数据是一个数组,所以要检索它的内容,你需要 data[0]
(第一个元素),它给你一个object {name":myName";,地址":我的地址"}
.
Why you need data[0]
because data is an array, so to its content retrieve you need data[0]
(first element), which gives you an object {"name":"myName" ,"address": "myAddress" }
.
访问对象属性的规则是:
And to access property of an object rule is:
Object.property
有时
Object["property"] // in some case
所以你需要
data[0].name
等得到你想要的.
set dataType: json
然后你需要使用 $.parseJSON()
解析它们并像上面一样检索数据.
set dataType: json
then you need to parse them using $.parseJSON()
and to retrieve data like above.
这篇关于如何访问 JSON 对象名称/值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!