无法从 php 检索 Ajax 调用中的 json 数据


Not able to retrieve json data in Ajax call from php

我能够在php中将数据转换为JSON格式,并且在将该数据发送到Ajax调用时,我无法获得详细信息。事实上,首先 Json 数据的长度显示 87,而实际上为 2。

我的 php 代码是

// credentials of MySql database.
$username = "root";
$password = "admin";
$hostname = "localhost"; 
$data = array();
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
  or die("Unable to connect to MySQL");
$selected = mysql_select_db("Angular",$dbhandle)
or die("Could not select Angular");
//execute the SQL query and return records
$result = mysql_query("SELECT id,name,password FROM User");
//fetch tha data from the database  
while ($row = mysql_fetch_array($result)) {
    $id = $row{'id'};
    $name = $row{'name'};
    $password = $row{'password'};
    $data[] = array('id' => $id, 'name' => $name, 'password' => $password);
}
echo json_encode($data);

它显示的输出是

[
    {
        "id": "1",
        "name": "Rafael",
        "password": "rafael"
    },
    {
        "id": "2",
        "name": "Nadal",
        "password": "nadal"
    }
]

我的阿贾克斯电话是

$.ajax({
    type: "GET",
    url: "ListUsers.php",
    success: function (dataCheck) {
        console.log(dataCheck.length);
        for(index in dataCheck) {
            /*
            console.log("Id:"+dataCheck[index].id);
                            console.log("Name:"+dataCheck[index].name);
                            console.log("Password:"+dataCheck[index].password);*/
        }
    },
    error: function () {
        alert("Error");
    }
 });

如果我的代码中有任何错误,请告诉我

数据类型设置为"JSON",一切就绪:

$.ajax({
  type: "GET",
  url: "ListUsers.php",
  success: function (dataCheck) {
    /* ... */
  },
  error: function () {
    alert("Error");
  },
  dataType: 'JSON'
});

success() 中的dataCheck是一个字符串。您必须像这样转换它:

var data = $.parseJSON(dataCheck);

现在你可以用它来循环,比如

data.forEach(function(item){
console.log(item.name)
});

这应该是你的 Ajax 调用:

$.ajax({
    type: "GET",
    url: "ListUsers.php",
    success: function (dataCheck) {
           var data = $.parseJSON(dataCheck);
           $(data).each(function(item){
                    console.log(item.name);
           });       
    },
    error: function () {
        alert("Error");
    }
 });