我有一个简单的登录表单,使用javascript,ajax和php,它会询问用户名和密码。它检查'message'变量的值以查看是否要提交。
test.php的
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<script src="ecommercescript.js" defer="true"></script>
</head>
<body>
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#login">Sign In</button>
<div id="login" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Sign In With Your Account</h4>
</div>
<div class="modal-body">
<form id="loginForm" class="form-horizontal" role="form" action="login.php" method="post" onsubmit="return validateForm()">
<div class="form-group">
<label class="control-label col-sm-2" for="usr">Username:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="usr" placeholder="Enter your username" name="usr">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="pwd">Password:</label>
<div class="col-sm-10">
<input type="password" class="form-control" id="pwd" name="pwd" placeholder="Enter your password">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-4">
<label id="prompt" class="control-label"> </label>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-4 col-sm-10">
<button type="submit" class="btn btn-primary">Submit</button>
<button type="button" class="btn btn-primary" onclick="clearInput()">Cancel</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</body>
</html>
ecommercescript.js
function validateForm() {
var usr = document.forms["loginForm"]["usr"].value.trim();
var pwd = document.forms["loginForm"]["pwd"].value.trim();
var message = "";
var validity = true;
if (usr.length > 0 && pwd.length > 0) {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
message = xmlhttp.responseText;
document.getElementById('prompt').innerHTML = message;
}
}
//value of 'message' gets lost here
xmlhttp.open("POST", "searchuser.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("username="+usr+"&password="+pwd+"")
} else {
message = "Username and/or password must be filled out";
document.getElementById('prompt').innerHTML = message;
validity = false;
}
if (message.length > 0) {
validity = false;
}
return validity;
}
function clearInput() {
document.getElementById('usr').value = "";
document.getElementById('pwd').value = "";
}
searchuser.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "ecommerce";
//Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
//Check connection
if ($conn->connect_error) {
die("Database connect failed: " . $conn->connect_error);
}
$username = $_REQUEST["username"];
$password = $_REQUEST["password"];
$message = "Account does not exist";
$sql = "SELECT * FROM tbl_users";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
if ($row['username'] == $username and $row['password'] == $password) {
$message = "";
break;
} else if ($row['username'] == $username and $row['password'] != $password) {
$message = "Incorrect password";
}
}
}
$conn->close();
echo $message;
?>
我的问题是xmlhttp.onreadystatechange中'message'的值丢失,因此脚本无法验证并始终提交表单。我已经评论了它丢失的部分。需要你的帮助。
答案 0 :(得分:0)
你基本上有这个:
When done with HTTP request {
Do a bunch of stuff;
Set message variable;
}
// comment about lost variable
Code to send HTTP request;
if (some stuff about message){
More stuff;
}
设置消息的代码将在发送请求后运行。此外,验证message
长度的代码将在您的HTTP请求解决之前运行(我认为这总是正确的,但也许快速的网络可以击败JS的条件?如果您知道,可以随意编辑)。
解决此问题的方法是:
When done with HTTP request {
Do a bunch of stuff;
Set message variable
if (some stuff about message){
More stuff;
}
}
// comment about sending request
Code to send HTTP request;
希望这有帮助!
答案 1 :(得分:0)
它不会迷路,你在设置之前尝试使用异步变量。如果你想这样做,你需要承诺对象。 q.js非常好。
function validateForm() {
var deferred = Q.defer();
var usr = document.forms["loginForm"]["usr"].value.trim();
var pwd = document.forms["loginForm"]["pwd"].value.trim();
var message = "";
var validity = true;
if (usr.length > 0 && pwd.length > 0) {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
message = xmlhttp.responseText;
document.getElementById('prompt').innerHTML = message;
deferred.resolve(message);
}
}
//value of 'message' gets lost here
xmlhttp.open("POST", "searchuser.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("username="+usr+"&password="+pwd+"")
} else {
message = "Username and/or password must be filled out";
document.getElementById('prompt').innerHTML = message;
deferred.resolve(message);
}
return deferred.promise;
}
或者在xmlhttprequest结算时发出自定义事件
function validateForm() {
var customEvent = new Event('messageResolved');
var usr = document.forms["loginForm"]["usr"].value.trim();
var pwd = document.forms["loginForm"]["pwd"].value.trim();
var message = "";
var validity = true;
if (usr.length > 0 && pwd.length > 0) {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
message = xmlhttp.responseText;
document.getElementById('prompt').innerHTML = message;
document.dispatchEvent('messageResolved', { message: message });
}
}
//value of 'message' gets lost here
xmlhttp.open("POST", "searchuser.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("username="+usr+"&password="+pwd+"")
} else {
message = "Username and/or password must be filled out";
document.getElementById('prompt').innerHTML = message;
document.dispatchEvent('messageResolved', { message: message });
}
}
或使用回调
function validateForm() {
var usr = document.forms["loginForm"]["usr"].value.trim();
var pwd = document.forms["loginForm"]["pwd"].value.trim();
var message = "";
var validity = true;
if (usr.length > 0 && pwd.length > 0) {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
message = xmlhttp.responseText;
document.getElementById('prompt').innerHTML = message;
callback(message);
}
}
//value of 'message' gets lost here
xmlhttp.open("POST", "searchuser.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("username="+usr+"&password="+pwd+"")
} else {
message = "Username and/or password must be filled out";
document.getElementById('prompt').innerHTML = message;
callback(message);
}
}
function callback(message){
}
答案 2 :(得分:0)
非常感谢,我设法通过将async参数设置为false来使其工作。无论如何,谢谢你的见解。
<强>前强>
//value of 'message' gets lost here
xmlhttp.open("POST", "searchuser.php", true);
<强>后强>
//value of 'message' gets lost here
xmlhttp.open("POST", "searchuser.php", false);