文件位置:
ajaxutils.js 封装的方法:
//创建request对象
function createXMLHttpRequest(){
try{
return new XMLHttpRequest();
}catch(e){
try{
return new ActiveXObject("Xsxml2.XMLHTTP");
}catch(e){
try{
return new ActiveXObject("Microsoft.XMLHTTP");
}catch(e){
alert("我们不在一个世界!");
}
}
}
}
/*请求方式,请求的url,是否异步,请求体,回调方法,服务器响应数据转换(来自XML,text,json)*/
//option对象包含method,url,asyn,params,callback,type
function ajax(option){
/*
* 1.得到xmlHttp
*/
var xmlHttp=createXMLHttpRequest();
/*
* 2.打开连接
*/
if(!option.method){//默认为GET
option.method="GET";
}
if(option.asyn==undefined){//默认为异步处理
option.asyn=true;
}
xmlHttp.open(option.method,option.url,option.asyn);
/*
* 3.判断是否为POST
*/
if("POST"==option.method){
xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
}
/*
* 4.发送请求
* get请求反正不会发送
*/
xmlHttp.send(option.params);
/*
* 5.注册监听
*/
xmlHttp.onreadystatechange=function(){
if(xmlHttp.readyState==4&&xmlHttp.status==200){
//获取服务器的响应数据,进行转换!
var data;
if(!option.type){
data=xmlHttp.responseText;
}else if(option.type=="xml"){
data=xmlHttp.responseXML;
}else if(option.type=="text"){
data=xmlHttp.responseText;
}else if(option.type=="json"){
var text=xmlHttp.responseText;
data=eval("("+text+")");
}
//调用回调方法
option.callback(data);
}
};
};
测试:
待请求的AServlet
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
/*
* 向客户端发送json串
*/
String str="{\"name\":\"zhangsan\",\"age\":18,\"sex\":\"male\"}";
System.out.println(str);
response.getWriter().print(str);
}
主程序:
<script type="text/javascript" src="./ajax-lib/ajaxutils.js"></script>
<script type="text/javascript">
window.onload=function(){
var btn=document.getElementById("btn");
btn.onclick=function(){
ajax(
{
url:"AServlet",
type:"json",
callback:function(data){
document.getElementById("h3").innerHTML=data.name+data.age+data.sex;
}
}
);
};
}
</script>