我有像这样的Json对象
{
" resultArr": [
{
"ID":"1",
"0":"1",
"APPROVAL LEVEL":"1",
"1":"1",
"WorkFlow Type Code":"1",
"2":"1",
"Employee Number":"825489602V",
"3":"825489602V",
"Employee Name":"Wajira Wanigasekara",
"4":"Wajira Wanigasekara"
}
]
}
我正在尝试打印resultArr的键和值。
例如,我想打印ID = 1 APPROVAL LEVEL = 1 ..就像那样
我可以使用此代码
获取ID,APPROVAL LEVEL ..的值$.ajax({
type: "POST",
async:false,
url: "<?php echo url_for('workflow/getApprovalByModuleView') ?>",
data: { viewName: viewName },
dataType: "json",
success: function(data){
alert(data.resultArr[0][3]);
}
});
但我想打印那些名字......
这意味着我想要打印data.resultArr数组的KEY和VALUE
我该怎么做?
答案 0 :(得分:3)
你使用键来选择值。我能想到的唯一方法是通过它们循环:
$.each(data.resultArr, function(index, value) {
alert(index + ': ' + value);
});
答案 1 :(得分:2)
我很确定您获得的data
变量是成功的参数,并不是您所期望的。
首先,弄清楚数据实际包含的内容。我建议安装Firebug而不是警告写:
console.dir(data);
同样要检查数据类型,请尝试:
console.log(typeof(data));
现在您知道您的数据实际返回的格式,您可以继续处理它。
答案 2 :(得分:1)
的javascript:
var array = {"key" : "value", "anotherkey" : "anothervalue"};
for (key in array){
document.write("For the Element " + "<b>"+array[key]+"</b>"
+ " Key value is " +"<b>"+key+"</b>"+"<br>");
}
这将从javascript中获取数组中的键和值。
你遇到的问题是我认为你正在访问两个不同的数组对象。
data.resultArr[0][3]
与data.resultArr[0]["3"]
不同,后者与data.resultArr [0]不相同[“员工编号”] . The first will give you the VALUE for
审批级别the second will give the the SECOND employee number and the last will give you the value for
员工编号`。
答案 3 :(得分:1)
您可以使用以下代码:
var json = {"resultArr":[{"ID":"1","0":"1","APPROVAL LEVEL":"1","1":"1","WorkFlow Type Code":"1","2":"1","Employee Number":"825489602V","3":"825489602V","Employee Name":"Wajira Wanigasekara","4":"Wajira Wanigasekara"}]};
var data = json.resultArr[0];
for (var key in data){
document.write(key+":" + data[key]);
}
答案 4 :(得分:1)
也许这会有所帮助:
function getArrayKeyAndValue(array, index){ var count = 0; for (key in array){ if(++count == index) return [key, array[key]]; } } var array = {"key1" : "value1", "key2" : "value2", "key3" : "value3"}; document.write(getArrayKeyAndValue(array, 1));
输出为:“key1,value1”;
答案 5 :(得分:1)
var json = {"resultArr":[{"ID":"1","0":"1","APPROVAL LEVEL":"1","1":"1","WorkFlow Type Code":"1","2":"1","Employee Number":"825489602V","3":"825489602V","Employee Name":"Wajira Wanigasekara","4":"Wajira Wanigasekara"}]};
for(var key in json.resultArr[0]) {
console.log( key, json.resultArr[0][key] );
}