0

我是使用 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 中查看 JSON 响应resdiv,但 div idresdiv1是空的!也不alert(json_obj);提醒什么!文件有什么问题?

注意:我正在学习Zuch 教程

4

3 回答 3

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

演示

于 2013-11-09T07:24:20.273 回答
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());
于 2013-11-09T07:57:37.077 回答
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); 
  }
于 2013-11-09T07:35:43.377 回答