我想使用AJAX處理簡單的登錄表單。我認爲這很容易,但我無法完成所有工作。關於AJAX,PHP和處理表格
的index.php
<html>
<head>
<title>AJAX Login</title>
<script type="text/javscript">
var XMLHttpRequestObject = false;
if(window.XMLHttpRequest) {
XMLHttpRequestObject = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
}
function logIn() {
if(XMLHttpRequestObject) {
var obj = document.getElementById("show");
XMLHttpRequestObject.open("GET", "login.php");
XMLHttpRequestObject.onreadystatechange = function() {
if(XMLHttpRequestObject.readyState == 4
&& XMLHttpRequestObject.status == 200) {
obj.innerHtml = XMLHttpRequestObject.responseText;
}
}
XMLHttpRequestObject.send(null);
}
}
</script>
</head>
<body>
<form action="" method="post">
<table>
<tr>
<td>Username:</td>
<td><input type="username" name="username" /></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" name="password" \ /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" name="submit" value="login" onclick="logIn();" /></td>
</tr>
</table>
</form>
<div id="show">should go here</div>
</body>
</html>
的login.php
<?php
$username = "andrew";
$password = "andrew";
if($_POST['username'] != "") {
if($_POST['password'] != "") {
if(($_POST['username'] == $username) && ($_POST['password'] == $password)) {
echo "Login Success!";
}
else {
echo "Login Failure!";
}
}
else {
echo "You didn't enter a password";
}
}
else {
echo "You didn't enter a username";
}
?>
當我點擊 「登錄」 按鈕,沒有任何反應。 :(
我推薦你用一些JavaScript庫,例如jQuery的。這使AJAX變得如此簡單,並且正在處理所有(或幾乎所有)瀏覽器。 – Franz 2009-11-20 00:14:30