douweilei2307 2014-04-03 07:01
浏览 31
已采纳

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

I'm able to convert my data into JSON format in php and while sending that data to Ajax call, I'm not able to get the details. In fact first the length of Json data shows 87, where it is actually 2.

My php code is

// 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);

Output it shows is

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

My Ajax call is

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

Please let me know if there is any thing wrong in my code

  • 写回答

3条回答 默认 最新

  • douvcpx6526 2014-04-03 07:07
    关注

    set the dataType to 'JSON' and you are all set:

    $.ajax({
      type: "GET",
      url: "ListUsers.php",
      success: function (dataCheck) {
        /* ... */
      },
      error: function () {
        alert("Error");
      },
      dataType: 'JSON'
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大