ajax processdata的作用,浅谈Ajax中的contentType和processData

contentType

在上次的项目中有提到,上传文件时,要将contentType和processData都设置为 false,现在给出我的理解(轻拍

contentType (default: ‘application/x-www-form-urlencoded; charset=UTF-8’)

When sending data to the server, use this content type. Default is “application/x-www-form-urlencoded; charset=UTF-8”, which is fine for most cases. If you explicitly pass in a content-type to $.ajax(), then it is always sent to the server (even if no data is sent).

Note: The W3C XMLHttpRequest specification dictates that the charset is always UTF-8; specifying another charset will not force the browser to change the encoding. Note: For cross-domain requests, setting the content type to anything other than application/x-www-form-urlencoded, multipart/form-data, or text/plain will trigger the browser to send a preflight OPTIONS request to the server.

上面是 Jquery 官网给的解释

简单的说,

对于上传文件contentType = multipart/form-data作为请求头是必须的,

而普通的 post 请求头是 application/x-www-form-urlencoded.所以如果没有设置成 false,是不能用来传输文件的

其次作为文件上传和作为普通字符串上传比如 id=” XXX” 在请求体中也是不同的。

这也就是为什么我们需要在 form 表单中加入enctype = “multipart/form-data” 的原因,由此才能让服务器正确的解析文件

processData

By default, data passed in to the data option as an object (technically, anything other than a string) will be processed and transformed into a query string, fitting to the default content-type “application/x-www-form-urlencoded”. If you want to send a DOMDocument, or other non-processed data, set this option to false.

处于同样的理由,如果 processData 为 true,会被处理并转换为 query string。所以这里也需设为 false。

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值