如何访问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.
例如:
[{名:MYNAME,地址:myAddress}]
在这种情况下,我的第一个警报给我不确定和第二/第三警报弹出来了:
In this case my first alert giving me undefined and second/third alert popup comes up with:
[{名:MYNAME,地址:myAddress}]
我如何按名称访问的价值,使我第一次警报填写为 MYNAME
这是名称
价值?
How can I access value by name so that my first alert filled out with myName
which is value of name
?
推荐答案
在JSON解析代替,你可以不喜欢followng:
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;
为什么需要数据[0]
,因为数据是一个数组,所以它的内容检索所需数据[0]
(第一个元素),它给你的对象 {名:MYNAME,地址:myAddress}
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
所以,你需要
So you need
数据[0]。名称
等来获得你想要的东西。
data[0].name
and so on to get what you want.
设置数据类型:JSON
则需要使用解析它们 $ parseJSON()
和检索数据等。上方。
set dataType: json
then you need to parse them using $.parseJSON()
and to retrieve data like above.
这篇关于如何访问JSON对象的名称/值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!