有register.html文件,其中javascript函数向db_check.php发出请求,验证登录凭据。下面的代码不能按预期工作,因为它返回错误的状态代码。我找到了一个解决方案,发现了这个链接:https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest?redirectlocale=en-US&redirectslug=DOM%2FXMLHttpRequest%2FUsing_XMLHttpRequest#section_3。它讨论了“当有一个XMLHttpRequest在窗口的onunload事件上被触发时:XMLHttpRequest实际上是在要关闭的窗口仍然存在时创建的,然后发送请求(即open())窗口已失去焦点,可能不同的窗口已经获得了关注。避免此问题的方法是在新窗口上设置一个监听器“激活”事件,当旧窗口触发“卸载”事件时,该事件将被设置。 任何人都可以通过代码片段解释引用的部分吗? 以下是代码:
<html>
<head>
<style>
.note {color: #FF0000;}
</style>
<script type="text/javascript">
function validateForm()
{
var xhr=false;
var username=document.getElementById(txt_name);
var pass=document.getElementById(txt_pass);
if(document.getElementById("txt_name").value.length==0)
var str="\nPlease enter username!";
else
str="";
if(document.getElementById("txt_pass").value.length==0)
str+="\nPlease enter password!";
if(str!="")
alert(str);
else
sendReq();
return false;
function sendReq()
{
var url1="db_check.php?uname="+username;
var url2= url1+"&password="+pass;
if (window.XMLHttpRequest)
{
xhr = new XMLHttpRequest();
}
else
{
if (window.ActiveXObject)
{
try
{
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {
}
}
}
if (xhr)
{
xhr.onreadystatechange = showValues;
xhr.open("GET", url2, true);
xhr.send();
}
else
{
alert("Sorry, but I couldn't create an XMLHttpRequest");
}
}
function showValues()
{
if (xhr.readyState == 4)
{
if (xhr.status == 200)
{
if(xhr.responseText=='false')
alert("Incorrect Username or password!");
else{
alert("Successfully logged-in!");
window.location.assign("register.html");
}
}
}
else
{
var outMsg = "There was a problem with the request " + xhr.status;
alert(outMsg);
}
}
}
</script>
</head>
<body bgcolor="#E6E6FA">
<h2>USC-net login</h2>
<form name="myForm" action="" method="post" id="myForm">
<fieldset>
<legend align="left">Login</legend>
Username: <input type="text" id="txt_name" name="txt_name" /><br>
Password: <input type="password" id="txt_pass" name="txt_pass" /><br>
<input type="hidden" name="formHidden"/>
<input type="submit" id="btn_submit" name="btn_submit" onclick="validateForm()" value="Submit"/><br>
<input type="button" id="btn_signup" name="btn_signup" value="Sign-Up" onclick="javascript:window.location='signup.php';">
<span class="note">*For first time users!</span><br>
</fieldset>
<br><br>
</form>
</body>
</html>