[英]Why does jQuery formData need contentType=false?
My question is about sending form data using jQuery.我的问题是关于使用 jQuery 发送表单数据。 I read that when the contentType line is omitted, jQuery defaults to x-www-formdata-urlencoded encoding.
我读到当 contentType 行被省略时,jQuery 默认为 x-www-formdata-urlencoded 编码。 This is what I think SHOULD be used.
这是我认为应该使用的。 But if contentType is set to false, it uses multipart/form-data encoding.
但是如果 contentType 设置为 false,则它使用 multipart/form-data 编码。
However, when contentType is omitted, the PHP says 'searchcity' index is undefined, meaning jQuery didn't successfully send 'searchcity' from my HTML input.但是,当 contentType 被省略时,PHP 会说“searchcity”索引未定义,这意味着 jQuery 没有成功地从我的 HTML 输入中发送“searchcity”。 When contentType is set to false, that means jQuery uses multipart/form-data, and PHP is able to find the index and everything works fine.
当 contentType 设置为 false 时,这意味着 jQuery 使用 multipart/form-data,并且 PHP 能够找到索引并且一切正常。
But in HTML, if you omit 'enctype', it defaults to x-www-formdata-urlencoding.但在 HTML 中,如果省略 'enctype',则默认为 x-www-formdata-urlencoding。 If I use
<form action = 'search.php' method = "POST"></form>
, it uses x-www-formdata-urlencoding and works fine.如果我使用
<form action = 'search.php' method = "POST"></form>
,它使用 x-www-formdata-urlencoding 并且工作正常。 I would NOT need to use <form action = 'search.php' method = "POST" enctype = "multipart/form-data"></form>
我不需要使用
<form action = 'search.php' method = "POST" enctype = "multipart/form-data"></form>
So how come when sending a form, HTML can send form data successfully to PHP using x-www-formdata-urlencoding, but jQuery requires multipart/form-data?那么为什么在发送表单时,HTML 可以使用 x-www-formdata-urlencoding 将表单数据成功发送到 PHP,而 jQuery 需要 multipart/form-data 呢?
I am sending only text, no files.我只发送文本,不发送文件。
<html>
<header><script src = "/jquery.js"></script></header>
<a href="/login.html">Login/Register</a> <br>
<form id = "searchform">
<input type = "text" name = "searchcity" size = "40"><br>
<input type = "button" id = "submit" value = "Search">
</form>
<script>
$("#submit").click(function(){
if( $("#searchform")[0].reportValidity() ){
var form = new FormData( $("#searchform")[0] );
$.post({
url:"/search.php",
processData:false, //prevents jquery from turning form to string
contentType:false, // this means to use multipart form encoding, but why?
data:form,
success:function(data){
alert(data);
}
});
}
});
</script>
</html>
https://pastebin.com/rMh3dr7r
contentType option to false is used for multipart/form-data forms that pass files.为 false 的 contentType 选项用于传递文件的 multipart/form-data 表单。 When one sets the contentType option to false, it forces jQuery not to add a Content-Type header, otherwise, the boundary string will be missing from it.
当将 contentType 选项设置为 false 时,它会强制 jQuery 不添加 Content-Type 标头,否则,将丢失边界字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.