AJAX 请求第一次不起作用,但之后起作用 [英] AJAX request doesn't work the first time but works thereafter

查看:64
本文介绍了AJAX 请求第一次不起作用,但之后起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个简单的函数,如 w3schools 官方网站上所示.我正在尝试运行 AJAX 请求的函数.

I'm making a simple function as it is shown on w3schools official website. I'm trying to run a function of an AJAX request.

我想除了代码仅在第一次失败后才运行之外,一切都运行良好.我的意思是,假设您是第一次来到我的网站,并且您第一次尝试提交,它只是刷新了页面而没有任何反应.

I guess it's all working well except the fact that the code ONLY runs after it fails the first time. I mean, let's say you just came the first time to my website and you try to submit the first time, it just refreshes the page and nothing happens.

据我所知,我尝试在每一行中使用 alert 函数进行调试,以确定请求是否真的被提出.我发现 readyState 在代码第一次运行时从 1 跳转到 4(在每个浏览器、不同的计算机中),但下次它会呈现 readyState 1、2、3 和 4 并爆炸它将工作并提交.

As far as I'm aware I tried to debug using alert functions in each line to find if the request was really being made. I found that the readyState jumps from 1 to 4 the very first time the code runs (in every browser, different computers), but next time it will render readyState 1, 2, 3 and 4 and BANG it will work and submit.

Javascript 函数代码(head 标签内)

function sendForm() {
        
    var criarRequest = new XMLHttpRequest();
    criarRequest.onreadystatechange = function() {  
        if (criarRequest.readyState == 4 && criarRequest.status == 200) {
            document.getElementById("contacts").innerHTML = criarRequest.responseText;
        } 
    };
    //var loading  = document.getElementById("contacts").innerHTML = "A enviar...";
    var inputEmail = document.getElementById("email").value;
    var inputMensagem = document.getElementById("mensagem").value;  
    criarRequest.open("POST", "sendEmail.php", true);
    criarRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    criarRequest.send("email="+inputEmail+"&mensagem="+inputEmail);
}

HTML 代码表单/输入

<form>
    <input style="width:220px; height:39px" type="text" id="email" placeholder="Email" /> 
    <br  /> <br  />
    <textarea style="width:220px; height:100px" id="mensagem" placeholder="Mensagem"></textarea>
    <br  /> <br  />
    <button id="enviar" onclick="sendForm()">Enviar</button>
</form>

推荐答案

实际上很简单:P 你的按钮是提交"的默认属性类型",当发生这种情况时,表单被提交导致刷新.添加 'type="button"' 以更改此功能,您不应再刷新以允许 ajax 完成其请求.

actually very simple:P your button is default attribute 'type' of "submit" and when that happens, the form gets submitted causing a refresh. Add 'type="button"' to change this functionality and you should not have a refresh anymore allowing the ajax to finish its request.

这篇关于AJAX 请求第一次不起作用,但之后起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆