为什么 AJAX POST 请求不起作用

Why does the AJAX POST request not work

本文关键字:不起作用 请求 POST AJAX 为什么      更新时间:2023-09-26
    <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);
}

注意:如果使用正确的代码缩进,则可以轻松避免此类问题。