我想从数据库中获取数据并显示到HTML表中,但是ajax URL不会调用PHP页面,并且无法获取成功的数据。
Ajax Call: I did not get JSON encoded data on success.
$.ajax({
url : 'FETCH.PHP',
dataType:'json',
contentType: "application/json",
success: function (data) {
var data = JSON.stringify(data);
var html = "";
for(var a = 0; a < data.length; a++) {
var firstName = data[a].firstname;
var email = data[a].email;
alert(email);
html += "<tr>";
html += "<td>" + firstName + "</td>";
html += "<td>" + email + "</td>";
html += "</tr>";
document.getElementById("data").innerHTML += html;
}
},
error: function(xhr, textStatus, error){
alert(xhr.statusText);
alert(textStatus);
alert(error);
}
});
这是我的PHP代码页,我想使用ajax调用移至此处 ==> FETCH.PHP页面
<?php
print_r("Hello");
include_once('database/db.php');
$getUsers = $connect->prepare("SELECT * FROM registration ORDER BY id ASC");
$getUsers->execute();
//$users = $getUsers->fetchAll();
$users = $getUsers->fetchAll(PDO::FETCH_ASSOC);
$items = array();
foreach($users as $u) {
//print_r($u);
$items[] = $u;
}
var_dump(json_encode($items);
exit();
?>
答案 0 :(得分:0)
摆脱所有输出,但回显JSON。
也不需要foreach
循环。 $items
只是$users
的副本。
<?php
include_once('database/db.php');
$getUsers = $connect->prepare("SELECT * FROM registration ORDER BY id ASC");
$getUsers->execute();
$users = $getUsers->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($users);
exit();
?>
答案 1 :(得分:0)
从ajax调用中删除两件事并运行我的代码。 dataType:'json', contentType:“ application / json”,
==>修改后的代码
$.ajax({
url : 'check.php',
success: function (data) {
data = $.parseJSON(data);
}
)};
==>我使用$ .parseJSON将json编码的字符串转换为数组。