下面是自己封装的一个Ajax工具函数
function MyAjax(){
//参数jason
this.myOptions={
"method":"GET", //请求的方式
"url":null,// 路径
"params":null,//参数
"type":"text",//servlet返回的字符串类型 text,jason,xml
"loading":null,
"success":function(){}
},
//创建XMLHTTPRequest对象
this.createXMLHttpRequest= function() { // 创建XMLHttpRequest对象
var xmlhttp;
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
try {
xmlhttp = new XMLHttpRequest();
if (xmlhttp.overrideMimeType) {
xmlhttp.overrideMimeType("text/xml");
}
} catch (e) {
}
}
}
return xmlhttp;
},
//处理传入的jason对象
this.processOptions=function(options){
var that =this;
for(var op in options){
var op=op.toLowerCase(); //将参数名转变为小写
that.myOptions[op]=options[op]; //将参数的值传递给调用对象
}
},
this.processURL=function(){
var that=this;
var URL=that.myOptions['url'];
var Method=that.myOptions['method'];
var params=that.myOptions['params'];
if(params){
if(Method.toUpperCase()==="GET"){
URL+=("?"+params);
that.myOptions['url']=URL;
}
}
},
this.callBack=function(request){
var that=this;
if(request.readyState==4){
if(request.status==200){
var type=that.myOptions['type'];
var returnValue=null;
if(type.toUpperCase()==='TEXT'){
returnValue=request.responseText;
}else if(type.toUpperCase()==='XML'){
returnValue=request.responseXML;
}else if(type.toUpperCase()==='JSON'){
var haha=request.responseText;
returnValue=eval("("+haha+")");
}
that.myOptions['success'](returnValue);
}else{
var loadingFun=that.myOptions['loading'];
if(loadingFun){
loadingFun();
}
}
}
},
this.startAjax=function(obj){
var that=this;
var XMLHttpRequest=that.createXMLHttpRequest();
that.processOptions(obj);
that.processURL();
XMLHttpRequest.open(that.myOptions['method'],that.myOptions['url'],true);
if (that.myOptions['method'].toUpperCase() === "POST") { // POST请求,添加请求头信息
xmlhttp.setRequestHeader("Content-Type",
"application/x-www-form-urlencoded;");
}
XMLHttpRequest.onreadystatechange=function(){
that.callBack(XMLHttpRequest);
}
XMLHttpRequest.send(null);
}
}
-----------------------------------------------------下面代码展在jsp页面的javascript中如何调用上面的工具函数。
function $(elementId) {
return elementId ? document.getElementById(elementId) : elementId;
}
function showInfo() {
var url = "servlet/CheckUsernameServlet";
var myAjax = new MyAjax();
myAjax.startAjax( {
url : url,
type : "json",
loading : function(){
$("info").innerHTML = "正在加载。。。";
},
success : function(returnValue) {
$("info").innerHTML = returnValue.name + "," + returnValue.age;
}
});
}