Ajax没有加载异步。表单提交时刷新页面

时间:2013-12-19 18:24:00

标签: javascript php ajax forms

我一直在尝试学习ajax,从我可以看到我的代码是正确的,但是当它回显了返回的json字符串时,它总是刷新页面。任何帮助将不胜感激!

  <script>      
    // Get XML HTTP Type
    function get_XmlHttp() {
        var xmlHttp = null;
            if(window.XMLHttpRequest) {
                xmlHttp = new XMLHttpRequest();
            }else if(window.ActiveXObject) {
                xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
        return xmlHttp;
    }

    function ajaxSuccess () {
        alert(this.responseText);
    }

    function ajaxrequest(oFormElement) {
        //Get The Correct XMLHTTP Object
        var request = new XMLHttpRequest();             

        request.open(oFormElement.method, oFormElement.action, true);
        request.setRequestHeader("Content-type","application/x-www-form-urlencoded");
        request.send(new FormData(oFormElement));
        return false;
        request.onreadystatechange = function() {
            if (request.readyState == 4 && request.status == 200) {
                alert("done");
                document.getElementById('comment_form').innerHTML = request.responseText;
            }
        }       
    }
    </script>


<form action="<?php echo $add_comment; ?>" method="post" enctype="multipart/form-data" id="comment_form" onsubmit="ajaxrequest(this);">
   <input name="user_id" type="hidden" value="<?php echo $user_id; ?>">
   <input name="user_message_id" type="hidden" value="<?php echo $user_message_id; ?>">
   <textarea id="new_comment" name="new_comment" cols="100" rows="5"></textarea>
   <input type="submit" value="post request"/>
</form>

3 个答案:

答案 0 :(得分:0)

使用Jquery库http://api.jquery.com/jQuery.ajax/,但是如果你想构建自己的脚本。请参阅w3c文档http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp

答案 1 :(得分:0)

正如Pointy指出的那样,您可能希望阻止提交按钮的默认点击事件触发

submitForm( event ) {
  event.preventDefault();
}

http://api.jquery.com/event.preventDefault/ &lt; - 我的不好......

只是为了澄清,那是你的完整代码吗?

答案 2 :(得分:0)

你必须阻止事件发生。在javascript中有一个常用的函数:

e.preventDefault; // e is the event that you need to pass to your function.

或更改
<input type="submit" value="post request"/>  到

<input type="button" onclick="ajaxrequest(this);" value="post request"/>

将要发生的是您的表单只会由javascript处理,并且由于表单提交,页面将重新加载。
只需为自己修改此方法,它就可以解决您的问题。

相关问题