1.封装
//封装秘诀:将相同的留下来,将不同的作为参数传递
function ajax (obj){
if(obj.type == null){
obj.type = "get";
}
if(obj.async == null){
obj.async = true;//默认使用异步
}
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if(xhr.readyState == 4){
if(xhr.status == 200){
obj.handle200(xhr)
}else if(xhr.status == 404){
if(obj.handle404 != null){
obj.handle404(xhr)
}
} else if(xhr.status == 500){
if(obj.handle500 != null){
obj.handle500(xhr)
}
}
}else{
if(obj.loading != null){
obj.loading(xhr)
}
}
}
if(obj.type.toLowerCase() == "get"){
if(obj.param != null){
xhr.open(obj.type,obj.url+"?"+obj.param,obj.async);
}else{
xhr.open(obj.type,obj.url,obj.async);
}
xhr.send();
}else if(obj.type.toLowerCase() == "post"){
xhr.open(obj.type,obj.url,obj.async);
xhr.setRequestHeader("content-type","application/x-www-form-urlencoded")
xhr.send(obj.param);
}
}
2.在servlet中的设置
//获取get方法的发送的数据
System.out.println(request.getParameter("name"));
System.out.println(request.getParameter("age"));
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//要返回数据,用流
PrintWriter out = response.getWriter();
out.write("{ "name" : "zhangsan" , "age" : 18 }");
}
3.调用
function doAjax(){
ajax({
"url" : "getdata" ,
"param" : "name=lisi&age=25" ,
"handle200" : function(xhr){
var obj = JSON.parse(xhr.responseText);
console.log(obj.name);
console.log(obj.age);
}
});
}