本教學由本站原創,轉載請註明出處
作者:www.111cn.net | 信箱:drise@163.com | QQ:271728967
上一節完成 reg.php 表單,本節實作 AJAX 核心 JavaScript 邏輯。
var xmlHttp = false;
function ajaxCreate() {
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e2) {
xmlHttp = false;
}
}
if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
xmlHttp = new XMLHttpRequest();
}
if (!xmlHttp) {
alert('Create Xmlhttp Fail');
return false;
}
}
function ajax() {
ajaxCreate();
var xmValue = document.getElementById("xm").value;
var url = "/boke/blog/type.php?txt=" + encodeURI(xmValue);
if (xmValue == null || xmValue.length > 20 || xmValue == "") return false;
xmlHttp.open("POST", url, true);
xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlHttp.send(xmValue);
xmlHttp.onreadystatechange = returnState;
}
function returnState() {
if (xmlHttp.readyState != 4) {
document.getElementById("divxm").innerHTML =
"<div id='phperblog_showinfo_red'><font color=red>正在驗證中,請稍後...</font></div>";
}
if (xmlHttp.readyState == 4) {
document.getElementById("divxm").innerHTML = xmlHttp.responseText;
}
}
關鍵點說明:
encodeURI() 編碼中文參數防止亂碼readyState == 4 表示請求完成,直接將伺服器回傳 HTML 寫入提示區塊