parseJSON to JSON rsponse in jquery-ajax 不起作用


parseJSON to JSON rsponse in jquery-ajax not working

我是使用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 id resdiv 中查看 JSON 响应,但div id resdiv1为空!此外,alert(json_obj);不会发出任何警报!文件有什么问题?

注意:我正在向Zuch教程学习

您无需再次解析 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);

查看演示

看看这个

// 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());

你能试试这个吗

   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); 
  }