H_MZ 2015-03-07 23:00 采纳率: 0%
浏览 34

使用AJAX解析JSON

I am trying to parse a JSON result with AJAX.

My JSON looks like this

[{
        "_id" : "54fb09b7d059bdf3107f9486",
        "lastName" : "Record",
        "firstName" : "First",
        "__v" : 0
    }, {
        "_id" : "54fb0a2fd059bdf3107f9487",
        "lastName" : "Record",
        "firstName" : "First",
        "__v" : 0
    }
]

I call this in Javascript

$.getJSON('api/people', function(data) {
       item3="+data.item3+"</p>");


  $.each(data,function(i,j){
    content ='<span>'+j[i].firstName+'<br />'+j[i].lastName+'<br /></span>';
  });
        alert(content);
  });

Unfortunately I get "Uncaught TypeError: Cannot read property 'firstName' of undefined" in the console.

Can someone please tell me how to properly parse this JSON?

  • 写回答

1条回答 默认 最新

  • 谁还没个明天 2015-03-07 23:10
    关注

    jQuery.each's second argument (the function executed for each element) takes two arguments (in your example, i and j), the first representing the key and the second the value, so there's no need for j[i].

    This should work:

    $.getJSON('api/people', function(data) {
      $.each(data,function(i, item){
        content ='<span>'+item.firstName+'<br />'+item.lastName+'<br /></span>';
      });
      alert(content);
    });
    
    评论

报告相同问题?