1.什么是 XMLHttpRequest 对象?
XMLHttpRequest 对象用于在后台与服务器交换数据。
XMLHttpRequest 对象是开发者的梦想,因为您能够:
- 在不重新加载页面的情况下更新网页
- 在页面已加载后从服务器请求数据
- 在页面已加载后从服务器接收数据
- 在后台向服务器发送数据
2.使用
2.1.GET请求
//1. 创建AJAX对象
const xhr = new XMLHttpRequest();
//2. 设置请求方法和url
xhr.open('GET','http://127.0.0.1:8000/server?a=100&b=200&C=300&=300');
//3. 发送
xhr.send();
//4. 事件绑定 处理服务端返回的结果
/*
on:when:当...时候
readystate: 是XHR对象中的一个属性,表示状态:
0(未初始化)
1(open方法调用完毕)
2(send方法调用完毕)
3(服务端返回部分结果)
4(服务端返回所有结果)
change:改变
*/
xhr.onreadystatechange = function(){
//作判断,是4(服务端返回了所有的结果)才处理数据
if(xhr.readyState === 4){
//判断响应状态码:200 404 403 401 500
//2XX 都是成功
if(xhr.status >= 200 && xhr.status < 300){
//处理服务端响应结果: 行 头 空行(咱不管) 体
//1. 处理响应行
// console.log(xhr.status);//状态码
// console.log(xhr.statusText);//状态字符串
// //2. 所有响应头
// console.log(xhr.getAllResponseHeaders());
// //3. 响应体
// console.log(xhr.response)
//设置result的文本
result.innerHTML = xhr.response +','+ xhr.status;
}else{
}
}
}
2.2.POST请求
//1.创建Ajax对象
const xhr = new XMLHttpRequest();
//2.初始化,请求体
xhr.open('POST','http://127.0.0.1:8000/server');
//设置请求头
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xhr.setRequestHeader('name','atGuiGu');
// 请求体内容类型
//3.发送
xhr.send('a=100&b=200&c=300');
// xhr.send('a:100&b:200&c:300');
//4.绑定响应事件
xhr.onreadystatechange=function (){
if(xhr.readyState === 4) {
if(xhr.status >=200 && xhr.status < 300) {
result.innerHTML = xhr.response;
}
}
}
2.3.jquery发送ajax请求
<script crossorigin="anonymous" src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script>
<script>
$('button').eq(0).click(function (){
$.get('http://127.0.0.1:8000/jqueryAll',{a:100,b:200},function (data){
console.log(data);
},'json');
});
$('button').eq(1).click(function (){
$.post('http://127.0.0.1:8000/jquery',{a:100,b:200},function (data){
console.log(data);
});
});
$('button').eq(2).click(function (){
$.ajax({
ulr:'http://127.0.0.1:8000/jqueryAll',
data:{a:100,b:200},
type:'GET',
dataType:'json',
//成功回调
success: function (data){
console.log(data);
},
timeout:2000,
//失败回调
error:function () {
},
//头信息
headers:{
c:300,
d:200,
}
},'json');
});
</script>
2.4.axios