JS Ajax步骤
1. 第一步:得到异步对象(XMLHttpRequest)
>大多数浏览器:var xmlHttp=new XMLHttpRequest();
>IE6.0: varxmlHtto=new ActiveXObject(“Msxml2.XMLHTTP”);
>IE5.5以前更早的版本: var xmlHtto=newActiveXObject(“Microsoft.XMLHTTP”);
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; } } } } |
2. 第二步(打开与服务器的链接)
* xmlHttp.open(); 用来打开与服务器的链接,他需要三个参数
>请求方式:get/post
>请求的URL:指定服务器的资源, 如 :“/servletA”
>请求是否为异步:如果为true表示异步发送,false表示同步
*如:xmlHttp.open(“GET”,”/servletA”,true);
例:xmlHttp.open("POST","<c:urlvalue='/servletB?method=doPost'/>",true);
//设置请求头 告诉浏览器post请求
xmlHttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
3. 第三步(发送请求体参数)
* xmlHttp.send(参数) 如果不给可能会发生错误,造成部分浏览器无法发送
>参数:就是请求体的内容! 如果是GET请求必须给出null
*如: xmlHttp.send(null)
*如: xmlHttp.send(“name=徐豪,pwd=123456”)
4. 第四步(获取响应的内容)
*在xmlHttp对象的事件上注册监听器:onreadystatechange
*xmlHttp对象的5个状态
>0状态:刚刚创建,还没有调用open方法
>1状态:表示请求开始了调用了open方法,但是还没调用send方法
>2状态:表示调用完了send方法
>3状态:表示服务器已经开始响应了,但是响应没有完成
>4状态:表示服务器响应结束了
*得到xmlHttp对象的状态
>var state=xmlHttp.readyState; //有可能是0 1 2 3 4
*得到服务器的响应码
>var status= xmlHttp.status; //有可能是200 300 400404 500….
*如何得到响应的内容
>xmlHttp.responseTest; //获得服务器响应的文本格式内容
>xmlHttp.responseXML; //获得服务器响应的XML格式内容
var xmlHttp=createXMLHttpRequest(); xmlHttp.onreadystatechange=function(){ //双重判断 判断异步对象的状态码=4 且 服务器响应码=200 才能正常获取数据 if(xmlHttp.readyState==4&&xmlHttp.status==200){ //获取服务器端响应的数据 var text=xmlHttp.responseText; } }; |
大题写法
//1.得到异步对象(XMLHttpRequest)
var xmlHttp = newXMLHttpRequest();
//2. 打开与服务器的链接 true代表异步 false代表同步
xmlHttp.open(“GET”,”/servletA”,true);
//3. 发送请求体参数
get请求:xmlHttp.send(null);
post请求:xmlHttp.send(“name=徐豪,pwd=123456”)
//4. 获取响应的内容
xmlHttp.onreadystatechange = function(){
if (xmlHttp.readyState==4 && xmlHttp.status==200){
// 请求成功 打印内容
console.log(xmlHttp.responseText);
}
}
JQ Ajax 步骤
jquery 提供了三种 ajax 请求的函数,分别为: $.ajax() , $.get() , $.post() $.getJSON
1.$.ajax()返回其创建的 XMLHttpRequest 对象。 $.ajax()
$.ajax({
url: //请求地址
type: “POST” //请求类型
dataType: “json” //返回数据的 类型 text/json/html
data: //传入的键值
success : function(data){
//回调函数,对返回的数据进行处理
}
});
$.get(),$.post(),$.getJSON方法:
请求成功时可调用回调函数。如果需要在出错时执行函数,请使用 $.ajax。
2.通过远程 HTTP GET 请求载入信息。 $.get()
$.get({ “填写url地址”,
{键值对的形式填写需要传入的数据}
function(data){
//回调函数,处理返回的数据
}
,json})
3.通过远程 HTTP POST 请求载入信息。 $.post()
$.post({“填写url地址”,
{键值对的形式填写需要传入的数据}
function(data){
//回调函数,处理返回的数据
}
,json})
4.通过 HTTP GET 请求载入 JSON 数据。(用于加载其他网域的JSON数据) $.getJSON(没用过)
$.getJSON({“外网地址”,
{键值对的形式填写需要传入的数据}
function(data){
//回调函数,处理返回的数据
}
,json})