以下是我的json回复
{
"head": null,
"body": {
"8431073": "CN0028-00"
},
"responseTime": null,
"leftPanel": null
}
我喜欢从身体获得关键和价值。下面是我的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
请帮帮我。谢谢你提前
答案 0 :(得分:3)
当您的回复进入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
});
}
}
答案 1 :(得分:0)
circuitList.length不是属性,使用Object.keys(circuitList).length。
var data = {"head": null,"body": {"8431073": "CN0028-00"},"responseTime": null,"leftPanel": null}
var result = data.body;
gethtmlvalues(result);
function gethtmlvalues(result){
debugger;
var circuitList = result;
var cktInstId = "";
var cktName = "";
if(circuitList != null){
//if(circuitList.length > 0){
$.each(circuitList,function(key, value){
console.log(key);
console.log(value);
cktInstId = key; // returns empty values
cktName = value; // returns empty values
});
//}
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>