<script>
function postComment() {
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("commentHint").innerHTML = xmlhttp.responseText;
}
var comment = document.getElementById("comment").value;
var id = document.getElementById("postID").value;
xmlhttp.open("POST", "commentpost.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("comment=" + comment + "&postID=" + id);
}
}
</script>
<form>
<div id="comment">
<textarea name="comment" id="comment" rows="4" cols="125" style="max-width: 950px; max-height: 140px;" placeholder="<?php echo $_SESSION["name"] ?>, Write Your Comment Here" class="form-control"></textarea><br>
<div id="commentHint"></div>
<input type="submit" onclick="postComment()" value="Submit Comment" class="btn btn-success btn-sm ">
<input type="hidden" id="postID" name="postID" value="<?php echo $post_id ?>">
</div>
</form>
我不知道为什么我的AJAX POST请求不起作用......
这是我对应的PHP文件中的POST变量:
$ comment = $ _POST [&#34;评论&#34;];
$ postID = $ _POST [&#34; postID&#34;];
当我点击提交评论按钮时,它会首先刷新页面并将我带回主页。它也不会激活PHP脚本..我是AJAX的新手,有人可以告诉我什么是错误的
答案 0 :(得分:0)
您的xmlhttp.send(...)
调用位于onreadystatechange
处理程序中,要调用处理程序方法,您需要发送请求,以便永远不会执行ajax方法。
负责发送请求的代码应该在处理程序方法之外。
function postComment() {
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("commentHint").innerHTML = xmlhttp.responseText;
}
}//need to close onreadystatechange here
var comment = document.getElementById("comment").value;
var id = document.getElementById("postID").value;
xmlhttp.open("POST", "commentpost.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("comment=" + comment + "&postID=" + id);
}
注意:如果使用正确的代码缩进,则可以轻松避免此类问题。