为什么AJAX POST请求不起作用

    <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>

I have no idea why my AJAX POST request isn't working... Here's the POST vars in my corresponding PHP FILE:
$comment = $_POST["comment"];
$postID = $_POST["postID"];

When ever I click the submit comment button it refreshes the page first and bring me back to the home page. It does not fire the php script either.. I'm new to AJAX can someone please tell me what's wrong

查看全部
duanaiguang1960
duanaiguang1960
2015/04/07 03:01
  • php
  • ajax
  • javascript
  • 点赞
  • 收藏
  • 回答
    私信
满意答案
查看全部

1个回复