JS实现的ajax发送数据重复

最近在做一个网页聊天室,但是在用ajax实现异步处理的时候,向服务器发送数据发送了两次,导致,我说一句会有两句回复。

先来看一下代码,问题主要还是出现在前端:

        <form id="data" method="post">
            <label><textarea class="chat_bottom" id="text" name="text"></textarea></label>
            <input class="image" id="image" type="file" name="image">
            <label class="image_box" for="image"></label>
            <button class="submit" id="submit" type="submit" onclick="chat()">发送</button>
            {% csrf_token %}
        </form>

<script>
    function chat() {
        var text = document.getElementById("text").value;

        var xmlhttp = createXMLHttpRequest();

        xmlhttp.open("POST","/webpage/Control/",true);
        xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
        xmlhttp.send("text="+text);

        xmlhttp.onreadystatechange = function () {
            if(xmlhttp.readyState === 4 && xmlhttp.status === 200){
                var temp = xmlhttp.responseText;
                console.log(temp);
                alert(temp);

                document.getElementById("mine_msg").innerHTML=text;
                document.getElementById("robot_msg").innerHTML=temp;
            }
        }
    }

    function createXMLHttpRequest() {
        var xmlHttp;
        try{
            xmlHttp = new XMLHttpRequest(); // 适用于大多数浏览器,以及IE7和IE更高版本
        } catch (e) {
            try {
                xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");  // 适用于IE6
            } catch (e) {
                try{
                    xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");   // 适用于IE5.5,以及IE更早版本
                } catch (e){}
            }
        }
        return xmlHttp;
    }
</script>

问题其实出现在form表单上,我用JS实现ajax向后端发送数据的同时,form表单也想后端发送了数据,而且ajax是异步,但form表单却是同步处理的,这就导致了既向后端发送了两次数据,而且还是同步处理。

只需要把form表单的标签注释掉就可以了。

原文地址:https://www.cnblogs.com/AlexKing007/p/12338119.html