实现:以面向对象的形式对ajax请求进行重构
/**
* 11
* 原始的
*/
window.onload = function() {
document.getElementById("ok").onclick = function() {
var xmlhttp = ajaxFunction();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {//响应完毕
if (xmlhttp.status == 200) {//成功响应
alert(xmlhttp.responseText);
}
}
}
xmlhttp.open("get", "../HelloWorldServlet", true);
xmlhttp.send(null);
}
}
// 10
function ajaxFunction() {
var xmlHttp;
try { // Firefox, Opera 8.0+, Safari
xmlHttp = new XMLHttpRequest();
} catch (e) {
try { // Internet Explorer
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
}
}
}
return xmlHttp;
}
/**
* 以面向对象的形式对ajax请求进行重构
*
* 20
*
*/
var ajaxObj = {
// key value
xmlhttprequest: '',
getXMLHttpRequest: function() {
var xmlHttp;
try { // Firefox, Opera 8.0+, Safari
xmlHttp = new XMLHttpRequest();
} catch(e) {
try { // Internet Explorer
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
}
}
}
return xmlHttp;
},
post: function(ajaxJSON) {
// 给 request 赋值
ajaxObj.XMLHttpRequest = ajaxObj.getXMLHttpRequest();
ajaxObj.XMLHttpRequest.onreadystatechange = function() {
if(ajaxObj.XMLHttpRequest.readyState == 4) {
if(ajaxObj.XMLHttpRequest.status == 200) {
ajaxJSON.callback(xmlhttp.responseText);
}
}
}
//
ajaxObj.XMLHttpRequest.open(ajaxJSON.method, ajaxJSON.url, true);
ajaxObj.XMLHttpRequest.send(ajaxJSON.data);
}
}
/**
* 在onload的时候调用
* 21
*/
window.onload = function() {
ajaxObj.post({
method: 'post',
url: '../HelloWorldServlet',
data: 'a=a',
callback: function(data) {
alert(data);
}
});
}