Ajax 请求的基本写法:
- get 请求
- get 请求传参
- post请求传参
get请求
// 创建XMLHttpRequest对象
const xhr = new XMLHttpRequest()
const url = 'http://localhost:3010/movie-types'
// 异步 ==> 第三个参数控制是否是异步请求
xhr.open('GET', url, true)
xhr.send()
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
console.log(xhr.responseText)
}
}
get请求传参
// 创建XMLHttpRequest对象
const xhr = new XMLHttpRequest()
let page = 1,
pagesize = 10
const url = `http://localhost:3010/movie-infos?page=${page}&pagesize=${pagesize}`
// 异步 ==> 第三个参数控制是否是异步请求
xhr.open('GET', url, true)
xhr.send()
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
console.log(xhr.responseText)
}
}
post请求(传参)
// 创建XMLHttpRequest对象
const xhr = new XMLHttpRequest()
const url = `http://localhost:3010/movie-infos/name`
// 异步 ==> 第三个参数控制是否是异步请求
xhr.open('POST', url, true)
// POST需要设置头信息
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
// post参数需要是查询字符串格式(&拼接 key=value&key=value)
xhr.send('name=杀手&page=1&pagesize=10')
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
console.log(xhr.responseText)
}
}
使用Promise 封装ajax 的get请求
function request(url) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest()
xhr.open('GET', url)
xhr.onreadystatechange = function () {
if (xhr.readyState !== 4) return
if (xhr.status == 200) {
const data = JSON.parse(xhr.responseText)
// 成功的回调
resolve(data)
} else {
// 失败的回调
reject(xhr.status)
}
}
xhr.send()
})
}
// 调用
request('http://localhost:3010/movie-types').then(res => {
console.log(res)
})