1.封装
//封装秘诀:将相同的留下来,将不同的作为参数传递
function ajax (type,url,async,param,handle200,handle404,handle500,loading){
if(async == null){
async = true;//默认使用异步
}
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if(xhr.readyState == 4){
if(xhr.status == 200){
handle200(xhr)
}else if(xhr.status == 404){
handle404(xhr)
} else if(xhr.status == 500){
handle500(xhr)
}
}else{
loading(xhr)
}
}
if(type.toLowerCase() == "get"){
if(param != null){
xhr.open(type,url+"?"+param,async);
}else{
xhr.open(type,url,async);
}
xhr.send();
}else if(type.toLowerCase() == "post"){
xhr.open(type,url,async);
xhr.setRequestHeader("content-type","application/x-www-form-urlencoded")
xhr.send(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("get","getdata",null,"name=zhangsan&age=20",function(xhr){
var str = xhr.responseText;
var obj = JSON.parse(str);
console.log(obj.name);
console.log(obj.age);
},function(xhr){
window.loaction.href = "404.html";
},function(xhr){
window.loaction.href = "500.html";
},function(xhr){
//数据加载中
});
}