我目前正在尝试这样做,所以我可以在不刷新页面的情况下删除我的评论,但由于我是AJAX的新手,我遇到了一些问题。我面临的一个问题是,到目前为止,我只使用load()
函数来调用整个PHP文件而不仅仅是文件内部的单个函数。
第二个问题是,通常当我加载新内容时,它们会被加载到专门制作的div
中,但是因为我试图删除而不是加载,我不知道该怎么做。
这是我的PHP代码。
echo "<form method='POST' action='".deleteComments($conn)."'>
<input type='hidden' name='id' value='".$row['id']."'>
<button id='delComments' type='submit' name='commentDelete'>Delete</button>
</form>";
function deleteComments($conn) {
if(isset($_POST['commentDelete'])) {
$id = $_POST['id'];
$sql4 = "DELETE FROM comments WHERE id='$id'";
$result4 = mysqli_query($conn, $sql4);
header("Location: index.php");
}
}
答案 0 :(得分:0)
您可以尝试使用此代码,希望此代码适合您。
<button id='delComments' data-delete-id = '".$row['id']."' type='submit' name='commentDelete'>Delete</button>
使用jquery就像
一样var delete_id = $(this).attr("data-delete-id");
$.ajax({
type: "POST",
url: "your_url",
data: ({id: delete_id}),
cache: false,
success: function(data){
alert(data);
}
});
您的commentFunction.php
function deleteComments($conn) {
$delete_id = $_POST['id'];
if(isset($delete_id)) {
$sql4 = "DELETE FROM comments WHERE id='$id'";
$result4 = mysqli_query($conn, $sql4);
echo 'delete comment';
}
}
答案 1 :(得分:0)
您可以使用define this Javascript,然后您可以从不同类型的事件中调用它,并在您的应用程序中执行AJAX。比如onClick(),onSelectedIndexChanged()等
<script type="text/javascript">
var HttpObject,vurl;
function genHttpobject() {
if(window.XMLHttpRequest) {
HttpObject=new XMLHttpRequest();
} else if(window.ActiveXObject) {
HttpObject=new ActiveXObject("Microsoft.XMLHTTP");
} else {
alert("Your Browser Does not support AJAX..Please use diff Browser");
}
}
function CallingMethod(val1,display_id) {
genHttpobject();
if(HttpObject!=null) {
HttpObject.open("GET",val1,true);
HttpObject.send(null);
HttpObject.onreadystatechange=function() {
if(HttpObject.readyState==4) {
document.getElementById(display_id).innerHTML=HttpObject.responseText
}
}
}
}