我的AJAX登录管理代码有什么问题?当我尝试使用我的用户名和密码登录时,它与PHP完美配合,但我的AJAX代码根本无法工作!有什么问题吗?
(注:我是jQuery和AJAx的新手)
我有index.php的代码:
<html>
<head><title>Login form</title></head>
<body>
<form id="myForm" action="testlogin.php" method="post">
username: <input type="text" name="username"> <br />
password: <input type="password" name="password"> <br />
<button id="submit">Login</button>
</form>
<div id="ack"></div>
<script type="text/javascript" src="jquery-2.0.2.js" ></script>
<script type="text/javascript" src="testajax.js"></script>
</body>
</html>
testlogin。php的代码如下:
<?php require_once("includes/connection.php"); ?> // starting the session.
<?php
$username = mysql_real_escape_string( $_POST["username"]);
$password = mysql_real_escape_string( ($_POST["password"]));
$sql = "SELECT * FROM users2 WHERE (username='$username' AND password='$password')";
$res = mysql_query($sql);
$row = mysql_fetch_array($res);
if($res === FALSE) {
die(mysql_error()); // TODO: better error handling
}
if( $row[0] > 0)
echo "Login Successful";
else
echo "Failed To Login";
?>
<?php include("includes/footer.php"); ?> //closing the session
最后我有这个testjax .js代码:
$ ("button#submit") .click(function() {
if ( $( "#username") .val() == "" || $( "#password") .val() == "" )
$("div#ack") .html("Please enter both username and password");
else
$.post ($("#myForm") .attr("action"),
$ ("#myForm :input") .serializeArryay(),
function(data) {
$("div#ack") .html(data);
});
$("#myForm") .submit(function) {
return false;
}
});
试试:
$("#myForm").submit(function(e){
e.preventDefault();
if ($('input[name="username"]').val() == "" || $('input[name="password"]').val() == "")
$("#ack").html("Please enter both username and password");
else
$.post($(this).attr("action"), $(this).serialize())
.done(function(data) { $("#ack").html(data); })
.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
});
我修正了你的间距(可能在你复制粘贴时发生),并把你的代码剪短了一点。
当您提交表单时,它将成功并运行.done(...)
或失败并运行.fail(...)
。这将帮助您准确地找出脚本失败的地方。