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。