XHR 的各种data类型对应的content-type header是什么?
1、application/x-www-form-urlencoded:最早的post请求中,参数通过浏览器url传递,不支持文件上传
POST /test HTTP/1.1
Host: foo.example
Content-Type: application/x-www-form-urlencoded
Content-Length: 27
field1=value1&field2=value2
2、multipart/form-data:可上传文件,也可键值对
POST /test HTTP/1.1
Host: foo.example
Content-Type: multipart/form-data;boundary="boundary"
--boundary
Content-Disposition: form-data; name="field1"
value1
--boundary
Content-Disposition: form-data; name="field2"; filename="example.txt"
value2
--boundary--
3、application/json:json类型
4、text/xml:XML类型
手写 XHR
1、get
var xhr = new XMLHttpRequest()
xhr.open("GET", url, false)
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
// 响应内容解析完成,可以在客户端调用了
if (xhr.status == 200) {
// 客户端的请求成功
alert(xhr.reponseText)
}
}
}
xhr.send(null)
2、post
var xhr = new XMLHttpRequest()
xhr.open("POST", url, false)
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
// 响应内容解析完成,可以在客户端调用了
if (xhr.status == 200) {
// 客户端的请求成功
alert(xhr.reponseText)
}
}
}
xhr.send(null)
3、综合:
const xhr = new XHRHttpRequest();
xhr.open([method], [url], 是否异步)
xhr.timeout = 5000; // ms
xhr.onload = () => {
console.log(xhr.responseType); // json text blob
console.log(xhr.response);
console.log(xhr.readyState); // 0 UNSENT 代理被创建,但尚未调用 open() 方法。 1 OPENED open() 方法已经被调用。 2 HEADERS_RECEIVED send() 方法已经被调用,并且头部和状态已经可获得。 3 LOADING 4 DONE
console.log(xhr.status); // 200
}
xhr.setRequestHeader()('key', 'value')
xhr.onreadystatechange = () => {}
xhr.send(data?);// post put 可 data