我想使用AJAX将登录电子邮件和密码发布到PHP页面
<form onsubmit="authenticate()">
<input type="text" placeholder="E-mail" name="email" id="email" />
<input type="password" placeholder="Password" name="password" id="password" />
<input type="submit" value="Login"/>
</form>
AJAX:
function authenticate() {
var email = document.getElementById("email").value;
var pass = document.getElementById("password").value;
var params = 'email=' + email + '&pass=' + pass;
var httpc = new XMLHttpRequest(); // simplified for clarity
var url = "http://127.0.0.1/login/login.php";
httpc.open("POST", url, true); // sending as POST
httpc.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
httpc.setRequestHeader("Content-Length", params.length); // POST request MUST have a Content-Length header (as per HTTP/1.1)
httpc.onreadystatechange = function() { //Call a function when the state changes.
if(httpc.readyState == 4 && httpc.status == 200) { // complete and no errors
if(httpc.responseText == "success") {
window.location.replace("files.html");
}
else if (httpc.responseText == "fail")
alert("Invalid details");
}
httpc.send(params);
}
}
如果select查询在身份验证后返回一行,它会回应“成功,否则它会回复”失败“
答案 0 :(得分:0)
我认为您的问题是您从函数params
内部发送onreadystatechange
,它现在可能无法正常工作,因为发送后“状态”会发生变化但是,在“状态”发生变化之前,您的代码不会发送任何内容......这应该解决它:
function authenticate() {
var email = document.getElementById("email").value;
var pass = document.getElementById("password").value;
var params = 'email=' + email + '&pass=' + pass;
var httpc = new XMLHttpRequest(); // simplified for clarity
var url = "http://127.0.0.1/login/login.php";
httpc.open("POST", url, true); // sending as POST
httpc.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
httpc.setRequestHeader("Content-Length", params.length); // POST request MUST have a Content-Length header (as per HTTP/1.1)
httpc.onreadystatechange = function() { //Call a function when the state changes.
if(httpc.readyState == 4 && httpc.status == 200) { // complete and no errors
if(httpc.responseText == "success") {
window.location.replace("files.html");
}
else if (httpc.responseText == "fail")
alert("Invalid details");
else
alert(httpc.responseText);
}
// Your httpc.send was here
}
httpc.send(params); // <-- should be here
}
在调用return false;
函数后,您还必须更改HTML以添加authenticate
,以防止表单执行“默认”操作(在“GET”中提交给自己“模式”。
<form onsubmit="authenticate(); return false;">
<input type="text" placeholder="E-mail" name="email" id="email" />
<input type="password" placeholder="Password" name="password" id="password" />
<input type="submit" value="Login"/>
</form>