不刷新頁面更新網(wǎng)頁
在頁面加載后從服務(wù)器請求數(shù)據(jù)
在頁面加載后從服務(wù)器接收數(shù)據(jù)
在后臺向服務(wù)器發(fā)送數(shù)據(jù)
下面是用js實現(xiàn)的ajax
//ajax
//創(chuàng)建一個XmlHttpRequest對象
var xmlHttpReq;
function createXmlHttpRequest()
{
? ? if(window.XMLHttpRequest)
? ? {//非IE
? ? ? xmlHttpReq = new XMLHttpRequest();
? ? }else
? ? { //IE
? ? ? xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
? ? }
}
//刪除學(xué)生信息
function dropValues(){
//獲取多選框的值
? ? obj = document.getElementsByName("studentInfo");
? ? createXmlHttpRequest();
? ? for(k in obj){
? ? ? ? if(obj[k].checked){
? ? ? ? //嘗試以異步的get方式訪問dropServlet
? ? ? ? var stuName = obj[k].value;
? ? alert("確認刪除:"+ stuName +"?");
? ? //path
? ? var url = "webDemo4/drop?oper=drop&sname="+stuName;
? ? //向服務(wù)器發(fā)送請求
? ? xmlHttpReq.open("get",url,true);
? ? //回調(diào)函數(shù)
? ? xmlHttpReq.onreadystatechange = processResponse;
? ? ? ? xmlHttpReq.send(null);
? ? ? ? }
? ? }
}
//增加學(xué)生信息
function addValues(){
? ? var name = $("#stuName").val();
? ? var sex = $("#stuSex").val();
? ? var age = $("#stuAge").val();
? ? var addr = $("#stuAddr").val();
? ? createXmlHttpRequest();
? ? alert("增加學(xué)生信息:"+name);
? ? //嘗試以異步的get方式訪問dropServlet
? ? var url = "webDemo4/drop?oper=add&sname="+name+"&"+"ssex="+sex+"&"+"sage="
? ? +age+"&"+"saddress="+addr;
? ? //向服務(wù)器發(fā)送請求
? ? xmlHttpReq.open("get",url,true);
? //指定響應(yīng)函數(shù)
? ? xmlHttpReq.onreadystatechange = processResponse;
? ? xmlHttpReq.send(null);
}
//響應(yīng)函數(shù)
function processResponse() {?
if (xmlHttpReq.readyState == 4) { // 判斷對象狀態(tài)?
? ? ? ? ? ? if (xmlHttpReq.status == 200) { // 信息已經(jīng)成功返回,開始處理信息?
? ? ? ? ? ? ? ? alert("刷新成功伯复!");
? ? ? ? ? ? ? ? $("#show").html(xmlHttpReq.responseText);
? ? ? ? ? ? } else { //頁面不正常?
? ? ? ? ? ? ? ? window.alert("您所請求的頁面有異常。");?
? ? ? ? ? ? }?
? ? ? ? }?
? ? ? }?
//修改學(xué)生信息
function modifyValues(){
? var name = $("#stuName").val();
? ? var sex = $("#stuSex").val();
? ? var age = $("#stuAge").val();
? ? var addr = $("#stuAddr").val();
? ? createXmlHttpRequest();
? ? alert("修改學(xué)生信息:"+name);
? ? //嘗試以異步的get方式訪問dropServlet
? ? var url = "webDemo4/drop?oper=modify&sname="+name+"&"+"ssex="+sex+"&"+"sage="
? ? +age+"&"+"saddress="+addr;
? ? //向服務(wù)器發(fā)送請求
? ? xmlHttpReq.open("get",url,true);
? //指定響應(yīng)函數(shù)
? ? xmlHttpReq.onreadystatechange = processResponse;
? ? xmlHttpReq.send(null);
}
//首次刷新
function fresh(){
createXmlHttpRequest();
var url = "webDemo4/drop?oper=query";
//向服務(wù)器發(fā)送請求
xmlHttpReq.open("get",url,true);
//指定響應(yīng)函數(shù)
? ? xmlHttpReq.onreadystatechange = processResponse;
? ? xmlHttpReq.send(null);
}
fresh();