在js中使用ajax請求一般包括三個步驟:
1、創建XMLHttp對象
2、發送請求:包含打開鏈接、發送請求
3、處理響應
在不使用不論什么的js框架的情況下。要想使用ajax。可能須要向以下一樣進行代碼的編寫
var xmlHttp = xmlHttpCreate();//創建對象
xmlHttp.onreadystatechange = function(){//響應處理
if(xmlHttp.readyState == 4){
console.info("response finish");
if(xmlHttp.status == 200){
console.info("reponse success");
console.info(xmlHttp.responseText);
}
}
}
xmlHttp.open("get","TestServlet",true);//打開鏈接
xmlHttp.send(null);//發送請求
function xmlHttpCreate() {
var xmlHttp;
try {
xmlHttp = new XMLHttpRequest;// ff opera
} catch (e) {
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");// ie
} catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
}
}
}
return xmlHttp;
}
console.info(xmlHttpCreate());
假設在比較復雜的業務邏輯里面使用這樣的ajax請求,會使得代碼非常臃腫,不方便重用,而且能夠看到,可能在server響應成功后要處理一個業務邏輯操作。這個時候不得不把操作寫在onreadystatechage方法里面。
為了方便代碼的重用我們能夠做出例如以下處理;
1、server響應成功后,要處理的業務邏輯交給開發者自己處理
2、對請求進行面向對象的封裝
處理之后看起來應該像以下這個樣子:
window.onload = function() {
document.getElementById("hit").onclick = function() {
console.info("開始請求");
ajax.post({
data : 'a=n',
url : 'TestServlet',
success : function(reponseText) {
console.info("success : "+reponseText);
},
error : function(reponseText) {
console.info("error : "+reponseText);
}
});
}
}
var ajax = {
xmlHttp : '',
url:'',
data:'',
xmlHttpCreate : function() {
var xmlHttp;
try {
xmlHttp = new XMLHttpRequest;// ff opera
} catch (e) {
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");// ie
} catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
}
}
}
return xmlHttp;
},
post:function(jsonObj){
ajax.data = jsonObj.data;
ajax.url = jsonObj.url;
//創建XMLHttp對象,打開鏈接、請求、響應
ajax.xmlHttp = ajax.xmlHttpCreate();
ajax.xmlHttp.open("post",ajax.url,true);
ajax.xmlHttp.onreadystatechange = function(){
if(ajax.xmlHttp.readyState == 4){
if(ajax.xmlHttp.status == 200){
jsonObj.success(ajax.xmlHttp.responseText);
}else{
jsonObj.error(ajax.xmlHttp.responseText);
}
}
}
ajax.xmlHttp.send(ajax.data);
}
};
上述代碼實現了相似jquery中的ajax操作,讀者有不懂的地方能夠慢慢思考或者在此留言
