jquery的ajax使用起来很轻松,但js的ajax却是其底层,也需要有所了解。
简单介绍一下,js的ajax需要哪些东西:
1.var xmlHttp = new xmlHttpRequest(),它是js的ajax实现的关键类
2.请求行 xmlHttp.open(),设置请求的方式、地址、是否异步,get的参数在地址后设置
3.请求头 xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded"),只需要post请求时设置
4.请求体 xmlHttp.send(),post的参数在这个函数中设置,get不需要填写
5.回调函数 xmlHttp.onreadystatechange = function(){...},请求成功后会调用此函数,具体对html操作的代码放在里面
js的ajax
onreadystatechange事件用来监控 readyState 的状态值 和 status 的状态值
status :200时为正常
readyState
- 调用了open之后状态为:1
- 调用了send之后,后台将要做出响应时为:2
- 开始接受后台向数据响应状态为:3
- 接受后台数据完成之后状态为:4
当readyState = 4,status = 200 的时候,需要将返回的时候,展示到客户端
js的ajax的具体实现——get
function doAjax() {
var xmlHttp;
//根据不同的浏览器,获取xmlHttpRequest()对象
if (window.XMLHttpRequest) {//判断window有没有XMLHttpRequest对象
xmlHttp = new XMLHttpRequest();
} else {//IE6以下,需要使用ActiveXObject组件
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
//onreadystatechange事件用来监控readyState的状态值
//当readyState = 4的时候,需要将返回的时候,展示到客户端
xmlHttp.onreadystatechange = function () {
console.log("xmlHttp.readyState=" + xmlHttp.readyState + ";xmlHttp.status=" + xmlHttp.status);
//过滤判断
//1.readyState必须为4,后台的数据才回反馈完毕
//2.本次提交的的状态代码:200(正常)
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
//后台数据回填到前台
document.getElementById("myFood").value = xmlHttp.responseText;
}
};
//get请求如果有参数就需要在url后面拼接参数
var food = document.getElementById("food").value;
//设置请求行,异步提交true
xmlHttp.open("get", "AjaxServlet?food=" + food, true);
//无需设置请求头
//设置请求体,get的参数在url拼接了,所以不需要在这个函数中设置
xmlHttp.send(null);
}
js的ajax的具体实现——post
function doAjax(){
var xmlHttp;
//根据不同的浏览器,获取xmlHttpRequest()对象
if(window.XMLHttpRequest){//判断window有没有XMLHttpRequest对象
xmlHttp = new XMLHttpRequest();
}else{//IE6以下,需要使用ActiveXObject组件
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
//onreadystatechange事件用来监控readyState的状态值
xmlHttp.onreadystatechange = function(){
console.log("xmlHttp.readyState="+xmlHttp.readyState+";xmlHttp.status="+xmlHttp.status);
//过滤判断
//1.readyState必须为4,后台的数据才回反馈完毕
//2.本次提交的的状态代码:200(正常)
if(xmlHttp.readyState == 4 && xmlHttp.status == 200){
//后台数据回填到前台
document.getElementById("myFood").value = xmlHttp.responseText;
}
};
//post如果有参数,就在请求体中传递
var food = document.getElementById("food").value;
//设置请求行,异步提交true
xmlHttp.open("get","AjaxServlet",true);
//设置请求头(GET方式忽略此步骤):setRequestHeader()
xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
//设置请求体,post的参数在这个函数中设置(如果有参数)
xmlHttp.send("food="+food);
}
Jquery的ajax
这个就比较简单了,只贴出最常用的一种
$.ajax({
type:"get",//get或者post
url:"abc",//请求的url地址
data:{},//请求的参数
dataType:"json",//json代表传入的json类型数据
timeout:3000,//3秒后提示错误
beforeSend:function(){
// 发送之前就会进入这个函数
// return false 这个ajax会停止,如果没有return false就会继续
},
success:function(data){// 成功拿到结果放到这个函数 data就是拿到的结果
},
error:function(){//失败的函数
},
complete:function(){//不管成功还是失败 都会进这个函数
}
})
// 常用 无注释
$.ajax({
type:"get",
url:"",
data:{},
dataType:"json",
success:function(data){
}
})
如果对您有所帮助,请点个赞支持一下作者~
这次一定!