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

时间:2014-04-03 07:01:48

标签: php jquery ajax json

我能够在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调用是

$.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");
    }
 });

如果我的代码中有任何问题,请告诉我

3 个答案:

答案 0 :(得分:2)

将dataType设置为' JSON'你们都准备好了:

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

答案 1 :(得分:1)

dataCheck内部成功()是一个字符串。你必须像这样转换它:

var data = $.parseJSON(dataCheck);

现在你可以在它中使用它来循环

data.forEach(function(item){

console.log(item.name)

});

答案 2 :(得分:0)

这应该是您的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");
    }
 });