ajax:发送异步请求:
第一步:ajax其实只需要一个对象:xmlHttpRequest;
大多数支持:var xmlHttp =new XMLHttpRequest();
第二步:XmlHttp.open() 用来打开与服务器的连接,需要三个参数。
请求方式:可以是Get或Post;
xmlHttp.open(“Get”,'AServlet',true);
第三步:xmlHttp。send(null);如果是get请求,不许给出null。
第四步:在xmlHttp对象的一个事件(onreadystatechange)他会在xmlHttpRequest对象的状态发生变化时调用。
0:初始化未完成 只是创建了一个xmlHttpRequest对象,还未调用open()方法。
1:请求一开始,open方法以调用,但还没有调用send()方法。
2:调用send()方法
3:开始读取服务器响应。
4:读取服务器响应结束(只关心服务器放回状态)
var state=xmlHttp.readState //得到服务器状态
var status =xmlHttp.status //得到服务器状态码
var content=xmlHttp.responseText //得到服务器响应的文本格式内容。
var content=xmlHttp.responseXml //得到服务器的响应的xml响应的内容,他是Document对象了。
xmlHttp.onreadstateChange =function (){
if(xmlHttp.readystate == 4 && xmlHttp.status==200){
var text =xmlHttp.responseText;
}
}
代码如下:
<script type="text/javascript"> function createXMLHttpRequest(){ //定义浏览器的支持 try{ return new XMLHttpRequest(); }catch(e){ try{ return new ActiveXObject("Msxml2.XMLHTTP"); }catch(e){ try{ return new ActiveXObject("Microsoft.XMLHTTP"); }catch(e){ alert("浏览器不支持"); throw e; } } } } window.οnlοad=function(){ var btn=document.getElementById("btn"); btn.οnclick=function(){//给按钮的点击事件注册监听 /** * ajax四步操作,得到服务器的响应 * 把响应的结果显示到h1元素中 * */ //得到异步对象 var xmlHttp =createXMLHttpRequest(); //打开与服务器的连接 xmlHttp.open("GET","./test/servlet/AServlet'",true); //发送请求 xmlHttp.send(null); //GET请求没有请求体,但也要给出null,不然firefox可能不会发送 //给异步对象的onreadystatechange事件注册监听器 xmlHttp.onreadystatechange=function(){ //双重判断 ,服务器响应结束,以及相应成功 if(xmlHttp.readyState == 4 && xmlHttp.status ==200){ var text= xmlHttp.responseText; var h1= document.getElementById("h1"); h1.innerText=text; } } } } </script>
另一种就是Post请求了
Post请求,在Servlet中只能用getPost来获取:
open:xmlHttp.open(“POST”....);
//这里需要比get方法都一步
需要设置Content-Type请求头:
xmlHttp.setRequestHeader(“Content-Type”,"application/x-www-form-urlencoded");
send:xmlHttp.send("username=hehe&password=123");//发送请求时指定