douyiqi9640 2015-06-01 05:49
浏览 17
已采纳

处理返回的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);
?>
  • 写回答

5条回答 默认 最新

  • douzuqin3467 2015-06-01 06:03
    关注

    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);
    })
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题