Fre*_*ddy 6 javascript php ajax jquery
我有一个没有目的地的锚链接,但它有一个onClick event:
<li><a href onClick='deletePost()'> Delete </a> </li>
Run Code Online (Sandbox Code Playgroud)
据我所知,由于PHP的性质和它是服务器端语言,我不能直接在JavaScript中执行PHP代码块,所以我必须利用AJAX这样做.
当delete点击链接时,我需要它来执行这个查询(del_post.php)
<?php include("connect.php");
$delete_query = mysqli_query ($connect, "DELETE FROM user_thoughts WHERE id = 'id' ");
?>
Run Code Online (Sandbox Code Playgroud)
我曾尝试使用类似的过去问题来理解AJAX,但由于相对较新,我无法完全掌握它的语言.这是我尝试过的:
function deletePost() {
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
xmlhttp.open("GET", "del_post.php", false);
xmlhttp.send();
}
}
}
Run Code Online (Sandbox Code Playgroud)
但是,单击该链接只会将URL更改为http://localhost/.
我相信(主要)问题是你的空“href”属性。删除它,或者将其更改为href="#"旧式href="javascript:void()"(在我看来,只需删除它)。
自从我使用 XMLHttpRequest 而不是像jQuery 的 .ajax这样的东西以来已经有一段时间了,但我认为你需要这样做(大多数情况下你需要.open/send在观察状态变化之前这样做):
var xmlHttpReq = new XMLHttpRequest();
if (xmlHttpReq) {
xmlHttpReq.open('GET', 'your-uri-here.php', true/false);
xmlHttpReq.onreadystatechange = function () {
if (xmlHttpReq.readyState == 4 && xmlHttpReq.status == 200) {
console.log('success! delete the post out of the DOM or some other response');
}
else {
console.log('there was a problem');
}
}
xmlHttpReq.send();
}
Run Code Online (Sandbox Code Playgroud)