我根据以前也有效的AJAX请求编写了一个登录脚本,但不知怎的,它停止了工作,尽管我没有改变代码中的任何特殊内容。 我正在使用XAMPP测试我的网站,但是当我尝试使用我的凭据登录时(如果它们是否正确无关紧要),我会被重定向到http://localhost:81/?username=admin&password=pass,这仍然不是正确的URL,应该是通过POST传递
我的HTML登录代码:
<div id="loginContainer">
<form>
<table class="loginMenu">
<tr>
<td class="loginTextAlign">Username: </td>
<td><input id="username" name="username" type="text" class="loginMenuTextBox"></td>
</tr>
<tr>
<td class="loginTextAlign">Password: </td>
<td><input id="password" name="password" type="password" class="loginMenuTextBox"></td>
</tr>
<tr>
<td></td>
<td><input id="mLogin" style="width:150px;" value="Login" type="submit" class="loginBtn"></td>
</tr>
</table>
</form>
</div>
我的JS文件:(与index.php文件中的jQuery一起嵌入)
$(document).ready(function() {
$('#enter').click(function () {
$('#splash').fadeOut(1000);
});
$('#mLogin').click(function(){
var username = $('#username');
var password = $('#password');
if(username.val() == ''){
alert('Please enter a valid username before submitting!');
return;
}
if(password.val() == ''){
alert('Please enter a valid password before submitting!');
return;
}
if(username.val() != '' && password.val() != ''){
var UrlToPass = 'action=login&username='+username.val()+'&password='+password.val();
$.ajax({
type : 'POST',
data : UrlToPass,
url : 'checklogin.php',
success: function(response){
if(response == 0){
hhide($('#loginerror'));
}
else if(response == 1){
window.location = 'comment.php';
}
}
});
}
return;
});
});
预先感谢您的帮助,如果您需要更多信息,请询问;)
答案 0 :(得分:0)
为您的<form>
提供身份证明并使用.submit()
您被重定向到
http://localhost:81/?username=admin&password=pass
的原因是因为表单在jQuery运行验证/ ajax调用之前提交。如果您向from添加提交事件处理程序将允许您在提交表单之前运行javascript / jQuery,那么您可以停止表单发布
preventDefault();
,允许您通过以下方式发送客户端用户名/密码AJAX。
如果您使用下面的源代码,则表单标记的ID应为UserLogin
$('#UserLogin').submit(function(event){
//Stop form submitting
event.preventDefault();
var username = $('#username');
var password = $('#password');
if(username.val()==''){alert('Please enter a valid username before submitting!');
return;
}
if(password.val()==''){alert('Please enter a valid password before submitting!');
return;
}
if(username.val() != '' && password.val() != ''){
var UrlToPass = 'action=login&username='+username.val()+'&password='+password.val();
$.ajax({
type : 'POST',
data : UrlToPass,
url : 'checklogin.php',
success: function(response){
if(response == 0){
hhide($('#loginerror'));
}else if(response == 1){
window.location = 'comment.php';
}
}
});
}
return;
});
如果您有任何疑问,请在下面留言,我会尽快给您回复。
我希望这会有所帮助。快乐的编码!