[英]How to properly use “data:” with jquery ajax request?
My code inside of function deletePost is not executing. 我的函数deletePost中的代码未执行。 This is because the contents of
$_GET['title']
is empty. 这是因为
$_GET['title']
为空。 I set the value of the title in the ajax using this line postTitle: $(this).siblings("h3.blog").text()
how come the value doesn't make it through the the php script? 我使用以下行
postTitle: $(this).siblings("h3.blog").text()
在ajax中设置标题的值postTitle: $(this).siblings("h3.blog").text()
为什么值无法通过php脚本实现?
index.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>';
}
?>
What am I doing wrong with $_GET
and the data from ajax? $_GET
和来自ajax的数据在做什么?
JavaScript 的JavaScript
$('.deletePost').click(function(){
$.ajax({
url:"scripts/post_action.php",
data: {action: "deletePost", postTitle: $(this).siblings("h3.blog").text()},
});
});
post_action.php 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);
}
?>
This is because the contents of
$_GET['title']
is empty.这是因为
$_GET['title']
为空。
The h3.blog
element is not a sibling of the delete button. h3.blog
元素不是删除按钮的同级对象。 It's a sibling of the parent of the delete button (the form
element). 它是删除按钮(
form
元素)的父级的同级。 To be flexible with your layout, you can use .closest
(traverse up) with .find
(traverse down): 为了灵活使用布局,可以将
.closest
(向上移动)与.find
(向下移动)一起使用:
$(this).closest('div.blog').find('h3.blog').text()
You have extra single quote. 您有多余的单引号。 Try to write:
尝试写:
function deletePost($mysqli, $title){
$sql = "DELETE FROM blog WHERE Title =" . $title;
mysqli_query($mysqli, $sql);
}
Also your code not protected from sql injection. 另外,您的代码不受SQL注入的保护。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.