开发者

Parsing JSON with jQuery .each method not working

开发者 https://www.devze.com 2023-03-08 20:33 出处:网络
I know this question might appear be too localized but I can\'t seem to get this to work. Here is the JSON my method returns:

I know this question might appear be too localized but I can't seem to get this to work.

Here is the JSON my method returns:

{ "dateTime" : "5/26/2011",
  "requestTime" : 0.1020102,
  "users" : [ { "Email" : "joem@email.com",
        "Location" : "home",
        "Name" : "Joe M",
        "UserId" : "42a7eae4-d4fe-49a3-93df-cd0cf219ac95"
      },
      { "Email" : "test@test.net",
        "Location" : "Work",
        "Name" : "Test Name",
        "UserId" : "97a444fb-6e3d-482c-a966-dbd3e0c739c8"
      }
    ]
}

The jQuery I'm using is like so:

$.ajax({
type: "POST",
url: "Home/GetUsers",
data: dataString,
suc开发者_如何学Pythoncess: function (data) {                      
     $.each(data.users, function(i, item) {
          $("#results").append('<p>' + item.Name + '</p>');
     });
}

I either get undefined, or nothing happens.

I get Object object if I do an alert(data) so I know it's returning something.

Obviously I'm doing something wrong here, so any help would be greatly appreciated.

Thanks!


alert(data.users) shows you undefined? Try adding dataType: 'text', and then do alert(data) and check you're getting the right json :/

This is working for me:

var data = { "dateTime" : "5/26/2011",
             "requestTime" : 0.1020102,
             "users" : [ { "Email" : "joem@email.com",
                "Location" : "home",
                "Name" : "Joe M",
                "UserId" : "42a7eae4-d4fe-49a3-93df-cd0cf219ac95"
              },
              { "Email" : "test@test.net",
                "Location" : "Work",
                "Name" : "Test Name",
                "UserId" : "97a444fb-6e3d-482c-a966-dbd3e0c739c8"
              }
            ]
           };
$(data.users).each(function(i, item) {
    $("#results").append('<p>' + item.Name + '</p>');
});


You could also try doing something like this:

$.post('Home/GetUsers', dataString, function(result) {
  $(result.users).each(function(i, item){
            $('#results').append('<p>'+item.Name+'</p>');
            });
  },'json'
});
0

精彩评论

暂无评论...
验证码 换一张
取 消