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

报告相同问题?

悬赏问题

  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程