執行個體:
1. Ajax登入的優點:如果輸入密碼錯誤,頁面無重新整理。
<script language="javascript">
//定義XMLHttpRequest對象執行個體
var http_request = false;
//定義可複用的http請求發送函數
function send_request(method,url,content,responseType,callback) {//初始化、指定處理函數、發送請求的函數
http_request = false;
//開始初始化XMLHttpRequest對象
if(window.XMLHttpRequest) { //Mozilla 瀏覽器
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType) {//設定MiME類別
http_request.overrideMimeType("text/xml");
}
}
else if (window.ActiveXObject) { // IE瀏覽器
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!http_request) { // 異常,建立對象執行個體失敗
window.alert("不能建立XMLHttpRequest對象執行個體.");
return false;
}
if(responseType.toLowerCase()=="text") {
//http_request.onreadystatechange = processTextResponse;
http_request.onreadystatechange = callback;
}
else if(responseType.toLowerCase()=="xml") {
//http_request.onreadystatechange = processXMLResponse;
http_request.onreadystatechange = callback;
}
else {
window.alert("響應類別參數錯誤。");
return false;
}
// 確定發送請求的方式和URL以及是否非同步執行下段代碼
if(method.toLowerCase()=="get") {
http_request.open(method, url, true);
http_request.setRequestHeader("If-Modified-Since","0");
}
else if(method.toLowerCase()=="post") {
http_request.open(method, url, true);
http_request.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
}
else {
window.alert("http請求類別參數錯誤。");
return false;
}
http_request.send(content);
}
// 處理返迴文本格式資訊的函數
function processTextResponse() {
if (http_request.readyState == 4) { // 判斷對象狀態
if (http_request.status == 200) { // 資訊已經成功返回,開始處理資訊
//alert(http_request.responseText);
alert("Text文檔響應。");
} else { //頁面不正常
alert("您所請求的頁面有異常。");
}
}
}
function registerCheck() {
document.getElementById("feedback_info").innerHTML = "";
var f = document.forms[0];
if(f.userAccount.value!="" && f.password.value !="" ){
document.getElementById("feedback_info").innerHTML = "正在處理請求,請稍後...";
send_request("POST","?service=page/Register&userAccount="+f.userAccount.value+"&password="+f.password.value,null,"text",showFeedbackInfo);
}
else {
document.getElementById("feedback_info").innerHTML = "請輸入正確的使用者名稱和密碼。";
}
}
function showFeedbackInfo() {
if (http_request.readyState == 4) { // 判斷對象狀態
//alert(http_request.responseText);
if (http_request.status == 200) { // 資訊已經成功返回,開始處理資訊
//alert(http_request.responseText);
if(http_request.responseText=='OK'){
document.forms[0].submit();
}
else{
document.getElementById("feedback_info").innerHTML = http_request.responseText;
}
} else { //頁面不正常
alert("您所請求的頁面有異常。");
}
}
}
</script>
2. Ajax實現定時重新整理。(待續)