通过以下内容,我得到了" undefined"在我的警报中返回()
我有以下AJAX:
$.ajax({
type: "GET",
url: "connect/database.php",
dataType: "json",
success: function(response){
alert(response);
}
});
以下PHP:
<?php
$servername = "localhost";
$username = "the_username";
$password = "the_password";
$dbname = "the_db";
// create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$array_result = array();
$sql = mysqli_query("select * from table where user = 'bobo'");
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$array_result[] = $row;
}
} else {
echo "0 results";
}
$conn->close();
print json_encode($array_result)
?>
答案 0 :(得分:0)
回应:“print json_encode($array_result)
打印即使没有结果。为什么?”
将print
放在if
之后的while
内。否则,emtpy $array_result
将被回应。
$array_result = array();
$sql = mysqli_query("select * from table where user = 'bobo'");
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$array_result[] = $row;
}
print json_encode($array_result)
} else {
echo json_encode(['error' => '0 results found']);
}
$conn->close();
你也想要为你的错误返回json,因为mkaatman建议
答案 1 :(得分:0)
更新:
$sql = mysqli_query("select * from table where user = 'bobo'");
$result = $conn->query($sql);
到此:
$sql = "select * from table where user = 'bobo'";
$result = $conn->query($sql);
另外,不要回显字符串,在数组中获取错误消息并对其进行json_encode:
echo json_encode(array(0=>'0 results'));
您可以通过以下方式打印结果:
$.ajax({
type: "GET",
url: "login.php",
dataType: "json",
success: function(response){
alert(response);
alert(response[0]);
alert(response[0]['id']);
}
});
其中id
是您的查询列之一。