下面是我的 json 响应
{
"head": null,
"body": {
"8431073": "CN0028-00"
},
"responseTime": null,
"leftPanel": null
}
我喜欢从 body 中获取键和值。下面是我的 ajax 调用,我想在其中获取键和值。但它返回空值。
$.ajax({
url: "ulhcircuit.json",
method: "GET",
contentType: "application/json; charset=utf-8",
success: function(data) {
result = data.body;
gethtmlvalues(result);
$("#dialog_loading").hide();
},
fail: function(xhr, ajaxOptions, thrownError) {
console.log(xhr);
$("#dialog_loading").hide();
}
});
function gethtmlvalues(result) {
var circuitList = result;
var cktInstId = "";
var cktName = "";
if (circuitList != null) {
if (circuitList.length > 0) {
$.each(circuitList, function(key, value) {
cktInstId = key; // returns empty values
cktName = value; // returns empty values
});
}
}
}
我希望 cktInstId 为 8431073,cktName 为 CN0028-00
请帮助我。提前致谢
最佳答案
当您的响应输入 gethtmlvalues
时,您将传递 data.body
,它基于您提供的 JSON,如下所示:
{ "8431073": "CN0028-00" }
这是一个普通的 JS 对象,而不是一个列表,并且 length
属性的存在并不意味着它包含的项目数量。这意味着您不需要长度检查(您正在比较 undefined > 0
)。您也不需要(错误地)命名的额外变量CircuitList
,您可以只使用result
。
function gethtmlvalues(result){
if(result != null){
$.each(result,function(key, value){
console.log(key, value); // this will print your key value pair
});
}
}
关于javascript - 如果对值是字符串,如何从 json 获取键和对值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39772317/