php - 使用 ajax 更新 mysql 结果(设置为已删除)而不刷新页面?
问题描述
我在名为 user_timeline 的 mysql 表中有数据行。
我在此表中有一个标记为已删除的列。
我正在运行查询以获取表中已删除 = 0 的所有结果。
$result = $conn ->query ("SELECT * FROM user_timeline WHERE user_id = '$p_id' AND deleted = '0' ORDER BY time_date DESC");
我想通过将其设置为 1 为用户提供能够在表中将结果标记为已删除的选项。
我想我可以通过创建一个链接来做到这一点,该链接将发布到我的页面 del_timeline.php
if(isset($_SESSION['CUSTOMER_ID'])){
echo '<a id="del_t" href="assets/del_timeline.php?t_id='.$row['id'].'"><div class="delete_timeline"></div></a>';
}
在 del_timeline.php 我有以下更新查询:
<?php
session_start();
include 'connect.php';
if(isset($_GET['t_id'])){
$t_id = $conn->real_escape_string($_GET['t_id']);
$myID = $_SESSION['CUSTOMER_ID'];
$conn->query("Update user_timeline Set deleted = '1' Where id = $t_id AND user_id = $myID") ;
}
?>
可以想象,我表中的每个结果都有一个特定/唯一的 ID。这样它就可以跟踪用户尝试将哪个结果设置为已删除。虽然这通过正常的 href 点击事件起作用。我正在尝试使用 ajax 运行它以避免页面刷新。
我不完全确定如何通过 ajax 传递 mysql $row 参数。我尝试了以下方法,但似乎不起作用。
<script>
$( "#del_t" ).submit(function( event ) {
event.preventDefault(); // <---- Add this line
$.ajax({
type: "POST",
url: "assets/del_timeline.php?t_id=$row['id']",
data: $( "#del_t" ).serialize(),
success: function(data) {
// print here
},
dataType: 'html' // for json response or 'html' for html response
});
</script>
请问有人可以告诉我哪里出错了吗?
解决方案
您不需要将 id 从 php 添加到 ajax 函数。您可以使用链接中的 href 地址。
$( "#del_t" ).click(function( event ) {
event.preventDefault();
$.ajax({
type: "POST",
url: $(this).attr('href'),
data: '',
success: function(data) {
// print here
},
dataType: 'html' // for json response or 'html' for html response
});
或者,更好的是,将 id 放入<a>
(例如在标题中)的属性中,在 php.ini 中使用 $_REQUEST。在 ajax 中,从该属性中获取 id 以将其传递到通过 post 发送的数据中。在 php 中:
echo '<a id="del_t" href="assets/del_timeline.php?t_id='.$row['id'].'" title="'.$row['id'].'"><div class="delete_timeline"></div></a>';
在 del_timeline.php 中:
if(isset($_REQUEST['t_id'])){
$t_id = $conn->real_escape_string($_REQUEST['t_id']);
//your code
}
阿贾克斯:
$( "#del_t" ).click(function( event ) {
event.preventDefault();
$.ajax({
type: "POST",
url: 'assets/del_timeline.php',
data: 't_id='+$(this).attr('title'),
success: function(data) {
// print here
},
dataType: 'html' // for json response or 'html' for html response
});