正确使用.ajax jquery方法?

时间:2013-11-28 06:08:45

标签: javascript php jquery mysql ajax

我希望请求在不更改网页的情况下从sql中删除记录。不幸的是,单击此按钮时实际上并没有删除记录。 post_action.php有什么问题导致删除失败?

post_action.php

 <?php
if($_GET['action'] == "deletePost")
        deletePost($_GET['title'])
function deletePost($title){
    $sql = "DELETE FROM blog WHERE Title = '$title';";
    mysqli_query($mysqli, $sql);
}
?>

Ajax请求:

$('#deletePost').click(function(){
    $.ajax({
        url:"post_action.php",
        data: {action: "deletePost",  postTitle: $(this).siblings("h3.blog").text()},
        success: function(result){
            $('ul.left').html(result);
        }
    });
});

的index.php

<?php
            include 'scripts/db_connect.php';
            include 'scripts/functions.php';
            sec_session_start();
            $sql = "SELECT * FROM blog";
            $result = mysqli_query($mysqli, $sql);
            while($row = mysqli_fetch_array($result))
            {
                echo'<div class="blog"><h3 class="blog">' . $row['Title'] . 
                "</h3><h3>" . $row['Date'] . "</h3><h3>" . $row['Tag'] . 
                "</h3><hr>";
                echo'<p class="blog">' . $row['Body'] . '</p><form name="postForm" 
                method="post" action="process_post.php">
                <input type="radio" name="postAction" 
                value="editPost" class="postButton"  type="button">Edit</input>
                <input type="radio" name="postAction" value="deletePost" 
                class="postButton" type="button">Delete</input>
                <input type="radio" name="postAction" value="commentPost" 
                class="postButton"  type="button">Comment</input>
                </form></div>';
            }

            ?>

3 个答案:

答案 0 :(得分:1)

问题; 你正在发送数据:

    `data: {action: "deletePost",  postTitle: $(this).siblings("h3.blog").text()}`,

但你正在使用

$_GET['title'] instead use $_GET['postTitle'] 

其次:如果请求成功,则调用成功函数。所以在这里你可以做很多事情,比如:

1. show a confirmation box sayin deleted successfully.
2. show a div giving confirmation.
3. remove the deleted row(should be done in all options)

答案 1 :(得分:0)

  

如果请求成功,则调用Success函数。该函数传递三个参数:从服务器返回的数据,根据dataType参数格式化;描述状态的字符串;和jqXHR

success: function(result){
     //perform function after succesfull deletion
     //for example : notifying user of record successfully deleted
     alert('DELETED SUCESSFULLY');
}

<强>参考

http://api.jquery.com/jQuery.ajax/

答案 2 :(得分:0)

这取决于您,您将从服务器端返回的内容作为删除的确认,例如,如果您编写deletePost这样的函数(假设$mysqli可用于您当前的范围)

function deletePost($title){
    // include 'scripts/db_connect.php';
    $sql = "DELETE FROM blog WHERE title = '$title'";
    mysqli_query($mysqli, $sql);
    if( mysqli_affected_rows($mysqli) ) return true;
    return false;
}

并像

一样使用它
if( deletePost ($_GET['postTitle'] ) ) {
    echo 'succeed';
}
else {
    echo 'failed';
}

所以,在ajax success函数中你可以使用类似的东西

success:function($data){
    if($data == 'succeed') alert('Record Deleted');
    else alert('Record Not Deleted');
}