我想停止通过 ajax 请求的结果提交表单... 这是我尝试使用的代码: 函数 chreg() 应该返回一个从 ajax 请求给定的 bool 值,但它没有!
Javascript:
function chreg() {
user = document.getElementById('nome').value;
passw1 = document.getElementById('passw1').value;
passw2 = document.getElementById('passw2').value;
mai = document.getElementById('mail').value;
dat = 'use='+encodeURIComponent(user)+'&pas='+encodeURIComponent(passw1)+'&pas2='+encodeURIComponent(passw2)+'&mail='+encodeURIComponent(mai);
htp = new XMLHttpRequest;
htp.onreadystatechange = function(){
if (htp.readyState == 4 && htp.status == 200){
if (htp.responseText == "true"){
alert('true');
return true;
}
else {
document.getElementById('er2').innerHTML = '<br/><h3>'+tag_esc(decodeURIComponent(htp.responseText))+'</h3>';
return false;
}
}
};
a = Math.random
htp.open("POST","checklog.php?a="+a,true);
htp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
htp.send(dat);
}
和 HTML:
<form action="reg.php" method="POST" onsubmit="return chreg(this);">
<table id="tab2"><tr><td>
<label for="user1">Username: <input type="text" name="user" id="nome" /></label></td> <td>
<label for="mail">Indirizzo e-mail: <input type="text" name="mail" id="mail" /></label> </td>
</tr>
<tr><td><label for="pass1">Password: <input type="password" name="pass1" id="passw1" /> </label></td>
<td><label for="pass2">Password (conferma): <input type="password" name="pass2" id="passw2" /></label></td></tr>
<tr><td colspan="2"><br /><input type="submit" class="st" value="Registrati" /></td> </tr>
</table>
<div id="er2"></div>
</form>
但是没用! 帮助 非常感谢!
最佳答案
您将无法使其按原样工作,因为默认情况下AJAX 异步。这意味着您的 chreg
方法会在请求完成且其结果已知之前启动请求并立即返回。这是一个问题,因为您无法在结果已知之前从 chreg
返回,因为您需要该结果才能知道返回什么。
一种解决方案是通过更改此处的第三个参数使请求同步:
// you will not need to set onreadystatechange at all
htp.open("POST","checklog.php?a="+a,false); // false = synchronous
htp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
htp.send(dat);
if (htp.responseText == "true"){
alert('true');
return true;
}
else {
document.getElementById('er2').innerHTML = '<br/><h3>'+tag_esc(decodeURIComponent(htp.responseText))+'</h3>';
return false;
}
这不是最佳解决方案,因为它可能最终会在请求期间锁定 UI,这是不可取的。然而,回到异步模型(没有这个问题)会更加复杂,因为它需要你“向后”做一些事情:
- 函数
chreg
被调用并发出 AJAX 请求;它总是返回false
(因此表单未提交) - 当您安装的
onreadystatechanged
处理程序检测到 AJAX 已完成时,它会检查响应。 - 如果响应在逻辑上是正确的(实际上需要提交表单),则使用
form.submit
去做。
关于javascript - 停止从 javascript ajax 请求提交,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10165093/