- 基础知识
- XMLHttpRequest
- 基本使用
- 响应类型
- 响应结果
- 使用示例
- 发送表单
- 封装请求类
- FETCH
- 请示步骤
- 响应头解析
- 响应内容解析
- 实例操作
- 发送请求 get
- 发送请求 post
浏览器天生具有发送HTTP请求的能力,比如在址栏输入内容,提交 FORM 表单等。 本章来学习通过JS程序来管理HTTP请求的能力。
使用JS脚本发送HTTP请求,不会带来页面的刷新,所以用户体验非常好。
XMLHttpRequest使用XMLHttpRequest发送请求,是一种存在很久的方案。 现代浏览器支持使用 fetch
的异步请求方式,fetch 基于 promise 异步操作体验更好。
使用XMLHttpRequest 发送请求需要执行以下几步
- 使用 new XMLHttpRequest 创建 xhr 对象
- xhr.open 初始化请求参数
- xhr.send 发送网络请求
- xhr.onload 监听请求结果
- xhr.onerror 请求中断等错误发生时的处理
通过设置 xhr.responseType 对响应结果进行声明,来对结果自动进行处理。
下面是可以使用的响应类型
类型说明text响应结果为文本json响应内容为JSON,系统会自动将结果转为JSON对象blob二进制数据响应documentXML DOCUMENT 内容 响应结果xhr.onload 用于处理响应完毕后的处理
使用以下属性来处理结果
1、xhr.status 为HTTP状态码 如 404/422/403等,当为200时为正确响应 2、xhr.statusText HTTP状态码内容,200时为ok,404 为Not Found 3、xhr.response 服务器端响应的内容
使用示例
const xhr = new XMLHttpRequest()
xhr.timeout = 5000
xhr.open('GET', 'http://tt.cc/testData/user.php')
xhr.send()
xhr.onload = function () {
if (xhr.status == 200) {
console.log(xhr.response)
} else {
console.log(`${xhr.status}:${xhr.statusText}`)
}
}
xhr.onerror = function (error) {
console.log(error)
}
users.php
"小明",
2 => "李四",
3 => "张三"
];
sleep(5);
echo $users[$_GET['id']];
发送表单
下面来使用 XMLHttpRequest 发送 POST 请求
后台服务 下面创建 users.php后台脚本(你可以使用你喜欢的后台脚本进行测试)
{
if (xhr.status == 200) {
console.log(xhr.response)
} else {
console.log(`${xhr.status}:${xhr.statusText}`)
}
}
}
下面结合 Promise 来构建一个 XHR 异步处理类,使异步请求操作的变得更简单。
class HD {
options = {
responseType: 'json',
}
constructor(method = 'GET', url, data = null, options) {
this.method = method
this.url = url
this.data = this.formatData(data)
Object.assign(this.options, options)
}
formatData(data) {
if (typeof data != 'object' || data == null) data = {}
let form = new FormData()
for (const [name, value] of Object.entries(data)) {
form.append(name, value)
}
return form
}
static get(url, options) {
return new this('GET', url, null, options).xhr()
}
static post(url, data, options) {
return new this('POST', url, data, options).xhr()
}
xhr() {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest()
xhr.open(this.method, this.url)
xhr.responseType = this.options.responseType
xhr.send(this.data)
xhr.onload = function () {
if (xhr.status != 200) {
reject({ status: xhr.status, error: xhr.statusText })
} else {
resolve(xhr.response)
}
}
xhr.onerror = function (error) {
reject(error)
}
})
}
}
// 使用HD.get静态方法发送GET请求
HD.get('http://tt.cc/testData/user.php?name=wgchen', {
responseType: 'text',
}).then((response) => {
console.log(response)
})
// 使用HD.post静态方法发送POST请求
let data = {title:'wgchen',url:'tt.cc'}
HD.post('http://tt.cc/testData/users.php', data, {
responseType: 'json',
}).then((response) => {
console.log(response)
})
users.php
'ycc'],
['name' => 'willem']
];
echo json_encode($articles);
发送请求 get
下面使用 FETCH 发送 GET 请求
fetch(`http://tt.cc/testData/users.php`)
.then(response => {
return response.json()
})
.then(articles => {
console.log(articles)
})
因为 fetch 结果是 promise 所以也可以使用 async/await
操作
async function query() {
const response = await fetch(`http://tt.cc/testData/users.php`)
const articles = await response.json()
console.log(articles)
}
query()
发送POST请求需要设置请求头 Request header
发送请求
发送的JSON类型需要设置请求头为 application/json;charset=utf-8
async function post() {
const response = await fetch(`http://tt.cc/testData/users.php`, {
method: 'POST',
headers: {
'Content-Type': 'application/json;charset=utf-8',
},
body: JSON.stringify({ name: 'wgchen' }),
})
if (response.ok) {
const articles = await response.json()
console.log(articles)
}
}
post()
后台响应
因为前台发送的是非表单数据,而是 JSON 字符串所以后台使用 php://input 来接收数据
关注
打赏
最近更新
- 深拷贝和浅拷贝的区别(重点)
- 【Vue】走进Vue框架世界
- 【云服务器】项目部署—搭建网站—vue电商后台管理系统
- 【React介绍】 一文带你深入React
- 【React】React组件实例的三大属性之state,props,refs(你学废了吗)
- 【脚手架VueCLI】从零开始,创建一个VUE项目
- 【React】深入理解React组件生命周期----图文详解(含代码)
- 【React】DOM的Diffing算法是什么?以及DOM中key的作用----经典面试题
- 【React】1_使用React脚手架创建项目步骤--------详解(含项目结构说明)
- 【React】2_如何使用react脚手架写一个简单的页面?