1. HTML Code(user_login.htm):
<html>
<head>
<meta charset="utf-8"/>
<title>AJAX Login</title>
<script src="user_login.js"></script>
</head>
<body>
<h3><a href="http://www.aleixcortadellas.com/main/2009/03/01/ajax-post/">AJAX Login</a></h3>
<form name="myform" id="myform">
<div id="msg" style="color:red;display:none;"></div>
Account: <input type="text" name="account"><br/>
Password: <input type="password" name="pwd"><br/>
<span id="btn"><input type="button" name="sb" id="sb" value="Login"></span><br/>
<span style="color:blue;">(tip: guest / guest)</span><br/>
<a href="index.htm">Home</a>
</form>
</body>
</html>
2. Javascript Code(user_login.js):
window.onload = initPage;
function initPage() {
// 取得「送出」按鈕的參考
var subBtn = document.getElementById("sb");
// 為按鈕加入事件處理器
subBtn.onclick = function () {
MakeRequest(); // 建立請求的函式
}
}
function createRequest() {
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
} else if(window.ActiveXObject) {
return new ActiveXObject("Microsoft.XMLHTTP");
} else {
alert("Your Browser Sucks!\nIt's about time to upgrade don't you think?");
}
}
var request = createRequest(); // 建立請求物件
function MakeRequest() {
form = document.getElementById("myform");
if (request != null) {
// 取得輸入的文字
var sPost = "";
for(i=0;i<form.elements.length;i++) {
inp = form.elements[i];
switch(inp.type) {
case "text":
case "textarea":
case "select-one":
case "radio":
case "password":
if (inp.name && inp.value) {
sPost+="&"+escape(inp.name)+"="+escape(inp.value);
}
break;
default:
break;
}
}
var url = "user_login.php?1=1";
// 利用 POST 方法、請求目的地 url、true 為非同步
request.open("POST", url, true);
// 回應處理函式 displayResult
request.onreadystatechange = displayResult;
request.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
request.send(sPost); // 送出請求
}
}
function displayResult() {
if (request.readyState == 4) { // 確認 readState
if (request.status == 200) { // 確認 status
var disp = document.getElementById("msg"); // 取得顯示位置
disp.innerHTML = request.responseText;
if (request.responseText=="Succcess") {
var btnInput = document.getElementById("btn"); // 取得按鈕位置
btnInput.style.display="none";
}
disp.style.display="block";
}
}
}
3. PHP Code(user_login.php):
<?php
$aRow =&$_POST;
$aStr = array();
if (!isset($aRow['account'])) $aRow['account']="";
if (!isset($aRow['pwd'])) $aRow['pwd']="";
if (!$aRow['account']) $aStr[] = "Enter account";
if (!$aRow['pwd']) $aStr[] = "Enter password";
if (!count($aStr)) {
if ($aRow['account']=="guest" and $aRow['pwd']=="guest") {
$aStr[] = "Succcess";
} else {
$aStr[] = "Account and password is not correct";
}
}
echo implode("<br>",$aStr);
?>
4. 寫好後, 執行 user_login.htm , 完成!
沒有留言:
張貼留言