我不知道如何将帖子标题放入jquery .ajax调用中。我能够创建和显示我的博客帖子,现在我正在尝试添加删除和编辑功能。我从删除开始,因为它显然更容易。如何将post数组中的博客标题导入到我的functions.js文件中,以便删除数据库中的匹配记录?还有......谢谢!
HTML
<?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><button id="editPost" type="button">Edit</button><button id="deletePost" type="button">Delete</button><button id="commentPost" type="button">Comment</button></div>';
}
?>
的functions.php
$function= $_POST['function'];
$title = $_POST['title'];
if($function == "deletePost")
deletePost($title)
function deletePost($title){
$sql = "DELETE FROM blog WHERE Title = '$title';";
mysqli_query($mysqli, $sql);
}
Functions.js
$(document).ready(function(){
$('#deletePost').on('click', function(){
$.ajax({
url: 'functions.php',
data:{function: "deletePost", title: "how do I get the blog title here"}
success: function(data){
//confirmation of deletion
}
});
});
});
答案 0 :(得分:1)
由于您需要POST请求,因此您需要在发出AJAX请求时指定它。
$.ajax({
url: 'functions.php',
type: 'POST', // specify request method as POST
...
});
应该这样做。
答案 1 :(得分:1)
试试这个
<?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><button id="editPost" type="button">Edit</button><a class="deletePost" rel="'. $row['Title'] .'" href="#" >Delete</a><button id="commentPost" type="button">Comment</button></div>';
}
?>
$(document).ready(function(){
$(".deletePost").on('click', function(){
$.ajax({
url: 'functions.php',
type: 'POST',
data:{function: "deletePost", title: $(this).attr('rel')}
success: function(data){
//confirmation of deletion
}
});
});
});