本文介绍如下内容:
三个浏览器原生支持的发送网络请求的方法。
const xhr = new XMLHttpRequest()open 方法准备发送请求:xhr.open(method, url, async, username, password)setRequestHeader 添加请求头:xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded')send 方法发送实际请求:xhr.send(null) 或 xhr.send(str) 表示 POST 的 bodyxhr.open 的第三个参数为一个 bool 值,表示是否异步发送请求,为 true 则需要在 xhr.onreadystatechange 事件监听方法上添加一个监听方法。当 xhr.readyState === 4 时表示请求发送成功并获取到响应。一般使用异步请求方式。
const xhr = new XMLHttpRequest()
xhr.onreadystatechange = function() {
if(xhr.readyState === 4) {
const status = xhr.status
if(status >= 200 && status < 300 || status === 304) {
const data = JSON.parse(xhr.responseText)
} else {
alert('request failed:', status)
}
}
}
xhr.open('get', '/', true)
xhr.send(null)
FormData 是 XMLHttpRequest Level 2 的内容,主要是为了简化表单序列化的操作。
const form = new FormData(document.forms[0])
form.append('a', 'b')
form.has('a') // true
form.get('a') // b
form.getAll('a') // ['b']
form.delete('c')
form.entries()
// 直接传入 FormData 对象,会自动根据表单的 enctype 设置请求头
xhr.send(form)
可以看到 FormData 的操作基本类似 Map。
fetch 返回一个 Promise,用于现代浏览器的网络请求。
fetch('/').then(response => response.json()).then(json => {
console.log(json)
})
默认情况下 fetch 只发送 GET 请求,可以通过 fetch 的第二个参数改变 fetch 的行为。init 对象的键值有:
body 请求的请求体,必须是 Blob、BufferSource、FormData、URLSearchParams、ReadableStream 或 String 的实例cachecredentials 携带 cookie 的策略,取值为:
omit 不发送 cookiesame-site 同源携带include 无论同源还是跨源都包含 cookiesame-siteheaders 请求头method 请求方法,默认为 GETmode 跨域的模式,取值为:
cors 遵循浏览器的 CORS 策略no-cors 仅简单请求支持 CORSsame-origin 不允许跨域redirect 重定向相关referrer HTTP referer 头相关携带 json
fetch('/send-json', {
method: 'POST',
// 必须指定 content-type
headers: {
'content-type': 'application/json'
},
body: JSON.stringfy({age: 1, name: 12})
})
携带表单参数
fetch('/send-form', {
method: 'POST',
// 必须指定 content-type
headers: {
'content-type': 'application/x-www-form-urlencoded'
},
// encoded 表单传参格式
body: 'a=1&b=2'
})
const form = new FormData()
form.append('name', 111)
form.append('age', 1232)
fetch('/send-form', {
method: 'POST',
// encoded 表单传参格式
body: form
})
发送文件
let imageFormData = new FormData();
let imageInput = document.querySelector("input[type='file']");
imageFormData.append('image', imageInput.files[0]);
fetch('/img-upload', {
method: 'POST',
body: imageFormData
});
// 这个 fetch()实现可以支持多个文件:
let imageFormData = new FormData();
let imageInput = document.querySelector("input[type='file'][multiple]");
for (let i = 0; i < imageInput.files.length; ++i) {
imageFormData.append('image', imageInput.files[i]);
}
fetch('/img-upload', {
method: 'POST',
body: imageFormData
});
// websocket 的 URL 必须为绝对路径,同时不受 CORS 策略影响,但是服务器可以判断请求来源
const socket = new WebSocket("ws://www.example.com/server.php");
// 发送数据
socket.send('hello world')
// 接受数据
socket.onmessage = function(event) {
let data = event.data;
// 对数据执行某些操作
};
更多内容见 MDN。