为什么 AJAX POST 请求不起作用
Why does the AJAX POST request not work
<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 vars:
$comment = $_POST["注释"];
$postID = $_POST["postID"];
当我单击提交评论按钮时,它会首先刷新页面并将我带回主页。它也不会触发php脚本。我是 AJAX 的新手,有人可以告诉我出了什么问题吗
您的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);
}
注意:如果使用正确的代码缩进,则可以轻松避免此类问题。
相关文章:
- 为什么 AJAX POST 请求不起作用
- AJAX请求不起作用,除非使用alert()
- Ajax Post请求不起作用
- IE8 jquery ajax头请求不起作用
- jQuery点击功能在获取请求后不起作用
- 使用Javascript的Ajax请求在iPhone浏览器中不起作用
- JQuery AJAX请求不起作用
- Node.js cors请求-异步示例不起作用
- Ajax 对 JSON 的请求不起作用
- React JS js 中的 AJAX 请求不起作用
- 对 URL 的 JSON-P 请求不起作用
- Jquery ajax请求不起作用
- 带有ajax xml请求的Node js脚本不起作用
- Ajax请求三次都不起作用,然后就起作用了
- AngularJS http.jsonp请求.then和.success函数不起作用
- Jquery ajax发布请求不起作用
- 外部AJAX请求不起作用
- 对SOAP服务的Preflight OPTIONS请求不起作用
- 使用AJAX发出POST请求;不起作用
- 第二个ajax请求在移动浏览器上不起作用