原生ajax
get
let xhr = new XMLHttpRequest()
xhr.open('get', 'http://www.liulongbin.top:3006/api/getbooks?id=1')
xhr.send()
xhr.onreadystatechange = function () {
if (this.readyState === 4 && this.status === 200) {
console.log(this.responseText)
}
}
post
let xht = new XMLHttpRequest()
xht.open('post', 'http://47.100.227.25:3000/users/register')
xht.setRequestHeader('content-type', "application/x-www-form-urlencoded")
xht.send('username=111&userpwd=111')
xht.onreadystatechange = function () {
if (this.readyState === 4 && this.status === 200) {
console.log(this.responseText)
}
}
jQuery中的ajax
$.ajax({
url: 'http://www.liulongbin.top:3006/api/getbooks?id=1',
method: 'GET',
// data: 'a=100&b=200',
data: { a: 100, b: 200 },
dataType: 'json',
success(res) {
console.log(res)
console.log(this)
},
error(xhr, info, err) {
},
timeout: 1000, // 1s 没有接收到响应就会取消本次请求
})
get请求
$.get('http://www.liulongbin.top:3006/api/getbooks',{id:1},res=>{
console.log(res)
})
post请求
$.post('http://47.100.227.25:3000/users/register','username=111&userpwd=111',res=>{
console.log(res)
})
promise-ajax
new Promise((resolve, reject) => {
$.get('http://www.liulongbin.top:3006/api/getbooks?id=1',res=>{
resolve(res)
})
}).then(res=>{
console.log(res)
})
axios
get
axios.get('http://www.liulongbin.top:3006/api/getbooks',{
params:{
id:1
}
})
.then(res=>{
console.log(res)
})
post
axios.post('http://47.100.227.25:3000/users/register','username=111&userpwd=111',{
username:111,
userpwd:111
})
.then(res=>{
console.log(res)
})
async - axios
async function fn(){
let res = await axios.get('http://www.liulongbin.top:3006/api/getbooks?id=1')
console.log(res)
}
fn()
```