处理返回的JSON数据

I'm querying my database using ajax (jquery) but the data I'm getting back is proving difficult to deal with. I did notice that others have posted similar issues and identified the PHP code (specifically how data is being allocated to the array) as being the issue. However I couldn't find a solution. The contents of my returned data (when I transform the returned data into a string) looks like this:

[{"id":"1","userName":"admin","userPassword":"admin","userEmail":"admin@admin.com","userRegistrationIP":"","registrationDateTime":"2015-05-28 21:22:54","userLastLogin":"2015-05-28 21:22:54"}]

I'd really like to be able to pull an individual element from the returned data, such as the userLastLogin field.

My ajax query:

$.ajax({

    url: 'authenticate2.php',
    type: 'POST',
    dataType: 'JSON',
    data: {
          username: $('#username').val(),
          },
     success: function (res) {

     $('#resultBox').text(res);

    }
});

My PHP below:

<?php

$con = mysqli_connect('127.0.0.1','root','','db1');
if (!$con) {
    die('Could not connect: ' . mysqli_error($con));
}

mysqli_select_db($con,"db1");
$sql="SELECT * FROM Users WHERE userName = 'admin'";

$result = mysqli_query($con,$sql);


$rows = array();
while($r = mysqli_fetch_assoc($result)) {
    $rows[] = $r;
}

echo json_encode($rows);
mysqli_close($con);
?>

This'll help you

JS

success: function (res) {
var res = [{"id":"1","userName":"admin","userPassword":"admin","userEmail":"admin@admin.com","userRegistrationIP":"","registrationDateTime":"2015-05-28 21:22:54","userLastLogin":"2015-05-28 21:22:54"}];
$.each(res,function(key,value){
     alert(res[key].id);
     alert(res[key].userName);
     alert(res[key].userPassword);
     alert(res[key].userEmail);
     alert(res[key].userRegistrationIP);
     alert(res[key].registrationDateTime);
     alert(res[key].userLastLogin);
})
}

Try this

    var json = '{"id":"1","userName":"admin","userPassword":"admin","userEmail":"admin@admin.com","userRegistrationIP":"","registrationDateTime":"2015-05-28 21:22:54","userLastLogin":"2015-05-28 21:22:54"}'; 
    for(var i = 0; i < json.length; i++) {
    var obj = json[i];

    console.log(obj.userLastLogin);
}

You can access individual elements from array like this (Client Side)

$.ajax({
  ....
  ....
  success: function (res) {

      alert(res[0].userLastLogin);

      // OR

      alert(res[0]['userLastLogin']);

   }
});

Check out this:

$.ajax({

    url: 'authenticate2.php',
    type: 'POST',
    success: function(res) {
          var response = $.parseJSON(res);
          console.log(res.userLastLogin);

    })

or you can just do this in your ajax success:

$.each(JSON.parse(res), function() {

  console.log(this[Object.keys(this)[6]]);

});

If u want to use only userLastLogin data then u can try this ,

while($r = mysqli_fetch_assoc($result)) {
    $rows['userLastLogin'] = $r['userLastLogin'];
}