jquery
// 基本用法無參數(shù)get請求
$.ajax({
url:"demo_test.txt",
success:function(result){
console.log(result);
}
}
// 需指定方法則增加method字段
$.ajax({
url:"demo_test.txt",
method:"POST",
success:function(result){
console.log(result);
}
}
// 有參數(shù),則增加data字段,有請求頭則增加headers字段耳峦,有錯誤處理增加error字段
// 默認(rèn)是按照表單提交post方法惧笛,data中雖然是json但是提交時轉(zhuǎn)成表單
$.ajax({
url:"demo_test.txt",
data:{a:10},
success:function(result){
console.log(result);
},
error:function(xhr,status,error){
console.log(error);
}
});
// data在post下是表單格式榛泛,在get下是querystring格式
// 通過以下方法指定為json格式[json格式本質(zhì)就是body里是json字符串综液,頭里是application/json]
$.ajax({
url:"demo_test.txt",
headers:{ contentType: "application/json"},
method:"POST",
data:JSON.stringify({a:10}),
success:function(result){
console.log(result);
}
});
fetch
// fetch的post表單數(shù)據(jù)用法
fetch(url,{
headers:{
'content-type': "application/x-www-form-urlencoded"
},
method:"POST",
body:"a=12&b=33",
})
.then(res=>res.json())
.then(data=>console.log(res))
.catch(e=>{})
// fetch的post json數(shù)據(jù)用法
fetch(url,{
headers:{
'content-type': "application/json"
},
method:"POST",
body:JSON.stringify({a:100}),
})
.then(res=>res.json())
.then(data=>console.log(res))
.catch(e=>{})
axios
// axios默認(rèn)是json類型的提交
axios({
url:"http://localhost:99?x=1",
method:"POST",
data:{a:12}
})
.then(res=>console.log(res.data))
// 如果想改成form則需要修改headers和data格式
axios({
url:"http://localhost:99?x=1",
method:"POST",
headers:{"Content-Type":"application/x-www-form-urlencoded"},
data:"a=12&b=23"
})
.then(res=>console.log(res.data))
簡寫
JQuery的get和post可以簡寫:
$.get(url,data,callback) // querystring格式
$.post(url,data,callback) // x-www-form-urlencoded格式
axios的get/post/put/delete等等都可以簡寫
axios.post(url,data).then(callback)