~~~~~~ Ajax 即“Asynchronous Javascript And XML”(异步 JavaScript 和 XML),是指一种创建交互式、快速动态网页应用的网页开发技术,无需重新加载整个网页的情况下,能够更新部分网页的技术。
使用原生AJAX发送请求一共四个步骤:
//1.创建对象
let xhr = new XMLHttpRequest();
//2.初始化,设置请求方法和url
xhr.open("GET","http://127.0.0.1:8000/server?a=100");
//设置响应体类型,返回结果如果是json形式则自动转成json对象
xhr.responseType='json';
//设置请求头
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded")
//3.发送
xhr.send();
//4.绑定事件,处理服务端返回的结果
//readystate是xhr对象中的属性,表示状态0,1,2,3,4
xhr.onreadystatechange = function() {
//判断(服务端返回了所有结果)
if(xhr.readyState === 4 && xhr.status===200){
//1.响应行
console.log(xhr.status);//状态码
console.log(xhr.statusText);//状态字符串
console.log(xhr.getAllResponseHeaders());//所有响应头
console.log(xhr.response);//响应体
//设置result的文本
result.innerHTML = xhr.response;
}
}
ontimeout
:设置超时的回调函数
onerror
:设置网络异常的回调函数
let xhr = new XMLHttpRequest();
//超时设置2s
xhr.timeout=2000;
//超时回调函数
xhr.ontimeout = function(){
alert("请求超时!");
}
//网络异常回调函数
xhr.onerror=function(){
alert("网络异常,稍后再试");
}
xhr.open("GET","http://127.0.0.1:8000/delay");
xhr.send();
if(xhr.readyState === 4 && xhr.status===200){
result.innerHTML = xhr.response;
}
使用abort()
函数可以取消请求
//获取元素对象
let btn = document.querySelectorAll("button");
let xhr = null;
btn[0].addEventListener("click",function(){
xhr = new XMLHttpRequest();
xhr.open("GET","http://localhost:8000/delay");
xhr.send();
})
//abort
btn[1].onclick = function(){
xhr.abort();
}
可以通过设置一个变量标识当前请求是否结束
//获取元素对象
let btn = document.querySelectorAll("button");
let xhr = null;
//标识变量
let isSending = false;//是否正在发送请求
btn[0].addEventListener("click",function(){
//判断标识变量
if(isSending) xhr.abort();//如果正在发送,则取消请求
xhr = new XMLHttpRequest();
isSending = true;
xhr.open("GET","http://localhost:8000/delay");
xhr.send();
xhr.onreadystatechange = function(){
if (xhr.readyState===4) {
isSending = false;
}
}
})
//abort
btn[1].onclick = function(){
xhr.abort();
}
头部需要引入jquery
<script crossorigin="anonymous" src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js">script>
$('button').eq(0).click(function(){
$.get('http://127.0.0.1:8000/jquery-server',{a:100,b:200},function(data) {
console.log(data);
},'json')
})
$('button').eq(1).click(function(){
$.post('http://127.0.0.1:8000/jquery-server',{a:100,b:200},function(data) {
console.log(data);
})
})
$('button').eq(2).click(function(){
$.ajax({
url:'http://127.0.0.1:8000/jquery-server',
data:{a:100,b:200},
type:'GET',
//响应体结果类型
dataType:'json',
//成功的回调
success:function(data){
console.log(data)
},
//超时时间
timeout:2000,
//失败的回调
error:function(){
console.log("请求失败")
},
//设置头信息
headers:{
}
})
})
首先引入axios
<script crossorigin="anonymous" src="https://cdn.bootcdn.net/ajax/libs/axios/0.19.2/axios.js">script>
//配置baseURL
axios.defaults.baseURL = 'http://127.0.0.1:8000'
btns[0].onclick = function(){
//Get请求
axios.get('/axios-server',{
params:{
a:100,
b:200
},
//请求头信息
headers:{
age:20
}
}).then(value=>{
console.log(value)
})
}
btns[1].onclick = function(){
//post请求
axios.post('/axios-server',{username:"admin"},{
params:{
a:100,
b:200
},
//请求头信息
headers:{
age:20
}
}).then(value=>{
console.log(value)
})
}
btns[2].onclick = function(){
//post请求
axios({
//请求类型
method:"POST",
//请求地址
url:'/axios-server',
//请求参数
params:{
a:100,
b:200
},
//请求头信息
headers:{
age:20
},
//请求体参数
data:{
username:"admin"
},
}).then(res=>{
console.log(res)
})
}
文档地址:https://developer.mozilla.org/zh-CN/docs/Web/API/fetch
const btn = document.querySelector('button');
btn.onclick = function(){
fetch('http://127.0.0.1:8000/fetch-server',{
//请求方法
method:"POST",
//请求头
headers:{
name:"hello"
},
//请求体
body:"username=admin&password=123456"
}).then(res=>{
// return res.text()
return res.json()
}).then(res=>{
console.log(res)
})
}