標籤:
<script type="text/javascript">
var http_request = false;
function createXMLHttpRequest() {
if (window.ActiveXObject) { // IE瀏覽器
http_request = new ActiveXObject("Msxml2.XMLHTTP"); //建立XMLHttpRequest對象
}else if (window.XMLHttpRequest) { // 非IE瀏覽器
http_request = new XMLHttpRequest(); //建立XMLHttpRequest對象
}
if (!http_request) {
alert("不能建立XMLHttpRequest對象執行個體!");
return false;
}
}
function getResult() {
var responseContext; //用於存放從伺服器返回的響應結果
if (http_request.readyState == 4) { // 判斷請求狀態
if (http_request.status == 200) { // 請求成功,開始處理返回結果
responseContext = http_request.responseText; //擷取伺服器的響應內容
if(responseContext.indexOf("true")!=-1){
alert("恭喜您!該使用者名稱有效!");
}else{
alert("抱歉!該使用者名稱已經被註冊!");
}
} else { // 請求頁面有錯誤
alert("您所請求的頁面有錯誤!");
}
}
}
function checkUsername(username) {
if (username.value == "") {
alert("請輸入使用者名稱!");
username.focus();
return;
} else {
createXMLHttpRequest();
http_request.onreadystatechange = getResult; //調用返回結果處理函數
http_request.open("GET","CheckUser?username="+username.value, true); //建立與伺服器的串連
http_request.send(null); //向伺服器發送請求
}
}
</script>
例子2:
<script type="text/javascript"> var xmlHttp = false; function createXMLHttpRequest(){ if(window.ActiveXObject){ xmlHttp = new ActiveXObject("Msxml2.XMLHTTP.3.0"); }else if(window.XMLHttpRequest){ xmlHttp = new XMLHttpRequest(); } } function startRequest(){ createXMLHttpRequest(); xmlHttp.onreadystatechange = handleStateChange; xmlHttp.open("GET", "http://localhost:8080/MyFirstWebPro/user.xml", false); xmlHttp.send(); } function handleStateChange(){ if(xmlHttp.readyState == 4){ if(xmlHttp.status == 200){ document.getElementById("results").innerHTML = xmlHttp.responseText; }else{ alert("您所請求的頁面有錯誤!"); } } } </script>
<body onload="startRequest();">
<div id="results"></div>
user.xml如下
<?xml version="1.0" encoding="gb2312"?><table> <tr> <th>姓名</th> <th>年齡</th> <th>性別</th> </tr> <tr> <td>王麗麗</td> <td>22</td> <td>女</td> </tr> <tr> <td>張芳</td> <td>22</td> <td>女</td> </tr> <tr> <td>張輝</td> <td>22</td> <td>男</td> </tr></table>
java ajax初始化