Ajax简介
Asynchronous javascript and xml,发送异步请求,传统获取网页数据的方式一般是客户端发送请求,服务器接收请求,根据请求响应刷新整个页面。而Ajax是一种不刷新页面也能刷新网页数据的一种技术,它能在等待页面传输数据的同时进行其他操作。
发送Ajax请求的5个步骤
1.创建1个异步对象;
2.设置请求方式和请求地址;
3.发送请求;
4.监听 状态的变化;
5.处理返回的结果
// 1.创建1个异步对象
var xmlhttp=new XMLHttpRequest();
//2.设置请求方式和请求地址
/*
method:请求类型 get/post
url:文件在服务器上的位置
async:true(异步)
*/
//get方法:
xmlhttp.open("GET","ajax-get.php",true);
//3.发送请求
xmlhttp.send();
//post方法:
xmlhttp.open("POST","04-post-ajax.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencode");
//3.发送请求
xmlhttp.send("userName=zs&userPwd=321");//传输内容自己设置
//4.监听状态的变化
xmlhttp.onreadystatechange=function(ev2){
/*
0:请求未初始化
1:服务器连接已建立
2:请求已接收
3:请求处理中
4:请求已完成,且响应已就绪
*/
if(xmlhttp.readyState===4){
// 判断是否请求成功
if(xmlhttp.status >=200 && xmlhttp.status<300 ||
xmlhttp.status===304){//请求状态码,200到300和304都是接收正常
//5.处理返回的结果
console.log("接收到服务器返回的结果");
}else{
console.log("没有接收到服务器返回的数据");
}
}
}
注意post请求要加上这句话
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencode");
而且post请求要传递的数据要写在send内,get请求的数据则写在url后。
方式1:封装原生js方法
直接用JavaScript的方法创建xmlhttprequest
对象、发送请求,但是为了使用方便,可以将函数封装起来,增加可重用性。
myAjax.js:
function obj2str(obj){//转换字符的方法
obj.t=new Date().getTime();
var res=[];
for(var key in obj){
//url中不可出现中文,故需转码
res.push(encodeURIComponent(key)+"="+encodeURIComponent(obj[key]));
}
return res.join("&");//返回结果由“&”连接
}
function ajax(option){ //函数参数为对象类型,按key名获取对应值。包括url,type(请求类型),data(数据),timeout(超时),sucess(回调函数),error
//0.转换内容
var str=obj2str(option.data);
//1.创建一个异步对象
var xmlhttp=new XMLHttpRequest();
//2.
if(option.type.toLowerCase()==="get"){//实现type值不区分大小写
xmlhttp.open(option.type,option.url+"?"+str,"true");
//3.
xmlhttp.send();
}else{
xmlhttp.open(option.type,option.url,"true");
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencode");
xmlhttp.send(str);
//3.
xmlhttp.send();
}
//4.
xmlhttp.onreadystatechange=function(ev2){
if(xmlhttp.readyState===4){
if(xmlhttp.status >=200 && xmlhttp.status<300 || xmlhttp.status===304){
//5.
option.success(xmlhttp);//成功的回调函数
}else{
option.error(xmlhttp);//失败的回调函数
}
}
}
// 判断超时
if(option.timeout){
timer=setInterval(function(){
console.log("中断请求");
xmlhttp.abort();
clearInterval(timer);
},option.timeout);
}
}
在html文件中,引入自己封装的Ajax方法,绑定事件,调用方法:
ajax({
url:"ajax-jquery.php",
data:{"userName":"张三","userPwd":"123456"},
type:"GET",
timeout:3000,
success:function(xhr){
alert(xhr.responseText)
},
error:function(xhr){
alert("请求失败");
}
})
方式2:用jQuery封装好的方法
其实方式1的封装js方法就是参考jq而写的。jQuery提供了ajax方法,可以通过 $.ajax()
直接调用,在html文件中调用的方式跟调用自己封装的js方法一样。不过需要先导入jq库。
<script src="jquery-3.5.1.js"></script>
//调用方法:
$.ajax({
url:"05-ajax-jquery.php",
type:"get",
data:"userName=lnj&userPwd=123",
success:function(msg){
alert(msg);
},
error:function(xhr){
alert(xhr.status);
}
})
其他
请求的url,我用的是php文件,在php中用echo输出就可以显示请求发送的内容。
<?php
echo $_GET["userName"];
echo $_GET["userPwd"];
?>