我是使用jquery的AJAX新手。我有一个json响应如下:
[{"customer_name":"Customer A"},{"customer_name":"Customer B"},{"customer_name":"Customer C"}]
我的ajax文件是:
function(result){
$('#resdiv').html(result);
console.log(result);
var json_obj = $.parseJSON(result);//parse JSON
alert(json_obj);
var output="<ul>";
for (var i in json_obj)
{
output+="<li>" + json_obj[i].customer_name + "</li>";
}
output+="</ul>";
$('#resdiv1').html(output);
}
虽然我可以在div resdiv
中查看JSON响应,但div resdiv1
为空! alert(json_obj);
也没有提醒任何事情!该文件有什么问题?
注意:我正在学习Zuch Tutorial
答案 0 :(得分:1)
你不需要再次解析json。只需做一次迭代并尝试这样
var json = [{"customer_name":"Customer A"},{"customer_name":"Customer B"},{"customer_name":"Customer C"}];
var output="<ul>";
$.each(json,function(key,val){
output+="<li>" + val.customer_name + "</li>";
});
output+="</ul>";
console.log(output);
参见 DEMO
答案 1 :(得分:1)
检查出来
// Need to parse if string.
var result = '[{"customer_name":"Customer A"},{"customer_name":"Customer B"},{"customer_name":"Customer C"}]';
var json_obj = $.parseJSON(result);//parse JSON
// No need to parse
var json_obj = [{"customer_name":"Customer A"},{"customer_name":"Customer B"},{"customer_name":"Customer C"}];
同时检查此
// if undefined, you don't have resdiv1 div or you have call function before your div render.
alert($('#resdiv1').html());
答案 2 :(得分:0)
你能试试吗
function(result){
$('#resdiv').html(result);
console.log(result);
var json_obj = $.parseJSON(result);
//parse JSON alert(json_obj);
var output="<ul>";
$.each(json_obj,function(key,val){
output+="<li>" + val.customer_name + "</li>";
console.log(key+":::"+val);
});
output+="</ul>";
$('#resdiv1').html(output);
}