我正在尝试使用php中的ajax和restapi从mysql数据库中获取数据。我希望我在搜索栏上插入一个值,它显示来自mysql的数据
api代码:
$response = array();
$posts = array();
$ID = $_POST['ID'];
$sql = "SELECT * FROM table WHERE client_id = ?";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("s", $ID);
$stmt->execute();
$result= $stmt->get_result();
$row = $result->fetch_assoc();
while($row=mysql_fetch_array($result)) {
$user_id=$row['id'];
$username=$row['username'];
$client_id=$row['client_id'];
$token=$row['token'];
$posts = array('id'=> $user_id, 'username'=> $username, 'client_id'=> $client_id, 'token'=> $token);
}
echo json_encode($posts);
$stmt = null;
$mysqli = null;
}
?>
这是ajax代码
$('document').ready(function()
{
$("#search").on("click", function(e){
e.preventDefault();
var to_search = $("#search_value").val();
console.log(to_search);
var formData = {
'ID' : to_search,
};
$.ajax({
type : 'POST',
url : 'search.php',
data : formData,
dataType : 'JSON',
encode : true,
success: function (data, response, status, xhr) {
if (response.result) {
console.log('done');
console.log(data);
}else{
console.log('fail');
console.log(data);
}
},
error: function (xhr, status, error) {
}
});
});
});
它不起作用,我只是想在浏览器控制台上打印结果。该按钮正在工作,因为它在控制台上显示我在搜索栏上插入的值 有什么建议吗?
答案 0 :(得分:1)
我没有在你的ajax调用中看到任何问题,但是我对你的PHP代码做了一些修改(这是未经测试的)。
$response = array();
$posts = array();
$ID = isset($_POST['ID']) ? $_POST['ID'] : 0; // Avoid warning because of missing "ID" post field
$sql = "SELECT * FROM table WHERE client_id = ?";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param('i', $ID); // ID's probably an integer, not a string
$stmt->execute();
$result= $stmt->get_result();
// Removed $row = $result->fetch_assoc();
while($row = $result->fetch_assoc()) { // Better use it this way
$user_id = $row['id'];
$username = $row['username'];
$client_id = $row['client_id'];
$token = $row['token'];
array_push($posts, array('id'=> $user_id, 'username'=> $username, 'client_id'=> $client_id, 'token'=> $token)); // Add the current loop element data to $posts
}
echo json_encode($posts);
$stmt = null;
$mysqli = null;