jquery-ajax中的parseJSON toJSON响应不起作用
问题描述:
I am new to AJAX using jquery. I have a json response as below:
[{"customer_name":"Customer A"},{"customer_name":"Customer B"},{"customer_name":"Customer C"}]
And my ajax file is :
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);
}
Though I can view the JSON response in div id resdiv
, the div id resdiv1
is empty ! Also alert(json_obj);
does not alerts anything ! Whats wrong with the file ?
NB: I am learning from Zuch Tutorial
我是使用jquery的AJAX新手。 我有一个json响应如下: p>
[{“customer_name”:“Customer A”},{“customer_name”:“Customer B”},{“customer_name”: “客户C”}]
code> pre>
我的ajax文件是: p>
function(result){
$('#resdiv')。html(result);
console.log(result);
var json_obj = $ .parseJSON(result); //解析JSON
alert(json_obj);
var output =“&lt; ul&gt;”;
for(var i in json_obj)
{
output + =“&lt; li&gt;” + json_obj [i] .customer_name +“&lt; / li&gt;”;
}
输出+ =“&lt; / ul&gt;”;
$('#resdiv1')。html(输出);
} \ n code> pre>
虽然我可以在div id resdiv code>中查看JSON响应,但div id resdiv1 code>是空的! 此外 alert(json_obj); code>不会发出任何警报! 该文件有什么问题? p>
注意:我正在学习 Zuch教程 p>
div>
答
You dont need to parse the json again.Simply do a iteration and try like this
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);
See DEMO
答
Can you try this
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);
}
答
check this out
// 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"}];
Also check this
// if undefined, you don't have resdiv1 div or you have call function before your div render.
alert($('#resdiv1').html());