我试图使用jQuery Ajax函数在MySQL数据库中删除一行。当我点击posts的"delete post"链接时,我希望它触发一个onClick
事件,该事件将运行delete行函数。
这是我到目前为止的代码:
首先显示带有链接的帖子,以删除每个帖子。
foreach($postarray AS $value){
echo '<div class="item">'.$value['post_title'].' , <a href="#" class="delete_link" value="'. $value['post_id'] .'">Delete Post</a></div>';
}
然后Jquery:
$(document).ready(function(){
$(".delete_post").click(function(){
var id = $(this).attr("value");
function deletePost(id){
$.ajax({
type: "POST",
url: "delete_post.php",
data: {id: id},
success: function(data){
alert("Post deleted");
}
})
}
});
});
和delete.php
代码:
//Start the session
session_start();
require_once('func/auth.class.php');
require_once('func/functions.php');
require_once('func/db.class.php');
// Check if user is logged in
if(!$_SESSION['is_admin'] || empty($_POST['id'])){
header("Location: index.php");
}
$post_id = $_POST['id'];
delete_post($post_id);
和delete_post()
函数:
function delete_post($post_id){
global $dbh;
$stmt = $dbh->prepare("DELETE FROM mjbox_posts WHERE post_id = ?");
$stmt->bindValue(1, $post_id, PDO::PARAM_INT);
$stmt->execute();
if($stmt->rowCount() != 0){
return TRUE;
}else{
return FALSE;
}
}
目前这个方法不能从数据库中删除帖子,我不知道为什么。
正如jcho360在评论中提到的,当绑定到click事件时,你在css类中有一个错误。
一旦你修复了,它仍然不能工作。触发click事件时,声明了一个删除帖子的函数,但没有调用它。一种修复方法是将其更改为以下内容:
$(document).ready(function(){
$(".delete_link").click(function(){
var id = $(this).attr("value");
$.ajax({
type: "POST",
url: "delete_post.php",
data: {id: id},
success: function(data){
alert("Post deleted");
}
});
});
});
这样,当click事件被触发时,您实际上是在发出请求。
进一步,我只是注意到,在ajax调用你请求"delete_post.php",但你提到你的php文件被称为delete.php。这也需要修复。
你可以在浏览器中使用检查器来查看当你点击链接时会发生什么。它有提出请求吗?id参数设置正确吗?等等