XHR 的各种data类型对应的content-type header是什么?手写 XHR

博客探讨了XHR(XMLHttpRequest)的三种data类型及其对应的content-type头:application/x-www-form-urlencoded用于基本键值对,multipart/form-data支持文件上传,application/json处理JSON数据。此外,还介绍了手写XHR的基本步骤,包括GET、POST和综合使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值