如何正确使用“数据:”与jquery ajax请求?

时间:2013-11-28 08:11:39

标签: javascript php jquery ajax

我的函数deletePost中的代码没有执行。这是因为$_GET['title']的内容为空。我使用这一行postTitle: $(this).siblings("h3.blog").text()在ajax中设置标题的值为什么值不通过php脚本?

的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="editPost" type="button">Edit</input>
              <input type="radio" name="postAction" value="deletePost" class="deletePost" type="button">Delete</input>
              <input type="radio" name="postAction" value="commentPost" class="commentPost" type="button">Comment</input></form></div>';
        }

        ?>

我对$_GET和ajax中的数据做错了什么?

的JavaScript

$('.deletePost').click(function(){
    $.ajax({
        url:"scripts/post_action.php",
        data: {action: "deletePost",  postTitle: $(this).siblings("h3.blog").text()},
    });
});

post_action.php

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

2 个答案:

答案 0 :(得分:1)

  

这是因为$_GET['title']的内容为空。

h3.blog元素不是删除​​按钮的兄弟。它是删除按钮(form元素)的的兄弟。为了灵活处理您的布局,您可以使用.closest(遍历).find(遍历):

$(this).closest('div.blog').find('h3.blog').text()

答案 1 :(得分:-1)

你有额外的单引号。试着写:

function deletePost($mysqli, $title){
    $sql = "DELETE FROM blog WHERE Title =" . $title;
    mysqli_query($mysqli, $sql);
}

此外,您的代码不受sql注入保护。