Fetch和Ajax比有什么优缺点?
//ajax-get:
var xhr = new XMLHttpRequest();
//请求行
xhr.open('get','./get.php?key1=val1&key2=val2');
//请求头
xhr.setRequestHeader('content-Type','text/html');
//请求主体
xhr.send(null);
xhr.onreadystatechange = function(){
if(xhr.readyState == 4 && xhr.status == 200){
console.log(xhr.responseText);
}
}
//ajax-post:
var xhr = new XMLHttpRequest();
//请求行
xhr.open('post','./ajax-post.php');
//请求头
xhr.setRequestHeader('content-Type','application/x-www-form-urlencoded');
//请求主体
xhr.send('key1=val1&key2=val2');
xhr.onreadystatechange = function(){
if(xhr.readyState == 4 && xhr.status == 200){
console.log(xhr.responseText);
}
} 优点:兼容性比较好$.ajax({
type: "POST",
url: url,
data: data,
dataType: dataType,
success: function(){},
error: function(){}
});
优缺点:
2. fetch
fetch("http://localhost:6888/test_get",{
method:"GET",
mode:"cors"
}).then(res=>{
return res.json()
}).then(json=>{
console.log("获取的结果", json.data)
return json
}).catch(err={
console.log("请求错误", err)
})
优点:
缺点:
3. axios
axios({
method: "post",
url:"/user/12345",
data:{
firstName:"Fred",
lastName:"Flintstone"
}
}).then(function(response){
console.log(response);
}).catch(function(error){
console.log(error);
});
优缺点: