【发布时间】:2018-06-24 10:15:44
【问题描述】:
我尝试从 ID 中返回数据库列的值。
我想在 ID 为“#name_page”的<span> 中显示它
我通过 POST "$(this).attr("id")" 发送 ID
我有我的 AJAX 调用
$(document).on('click', '.update_btn', function(e){
e.preventDefault();
$.ajax({
url:"fetch_single.php",
type:"POST",
data:{
user_id: $(this).attr("id"),
},
success:function(data) {
$('#name_page').val(data.name_page);
$('#user_id').val(user_id);
}
});
然后我在 fetch_single.php 中接收它
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "test";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT name_page FROM table WHERE id = '".$_POST["user_id"]."'
LIMIT 1");
$stmt->execute();
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
但不可能在我的网页中恢复价值
【问题讨论】:
-
使用 PDO 但不是
prepare()与占位符? -
看起来你需要一个
echo json_encode($stmt->fetch());在你的$stmt->execute();之后 -
@Sean 即使我的数据类型不是 json?
-
在
$('#name_page').val(data.name_page);中使用data.name_page表示您期待json -
@sean 谢谢我正在学习,你的评论澄清了我的问题。我正在继续挖掘问题..