先看下ajax请求:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
</body>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
<script>
var fd = new FormData();
fd.append("name", "wang");
$.ajax({
url: 'http://localhost:8080/test',
type: 'POST',
data:fd,
//processData:false
});
</script>
</html>
此时ajax请求并不成功,会报【TypeError: Illegal invocation】错误
再看下Jquery关于Ajax方法的doc文档关于processData和contentType 参数解释,
processData (default: true)
Type: Boolean
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.
大意是:默认情况下将传给data参数的值作为对象解析并作为请求参数,适合content-type:application/x-www-form-urlencoded的情况;默认是true,如果不想让Jquery处理数据,应该设置值为false。
contentType (default: 'application/x-www-form-urlencoded; charset=UTF-8')
Type: Boolean or String
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). As of jQuery 1.6 you can pass false to tell jQuery to not set any content type header. 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.
contentType默认值是【application/x-www-form-urlencoded; charset=UTF-8】,该值可以是boolean或String,如果是传输的数据对象是FormData,应该设置为false,所以传输FormData,ajax正确设置:
var fd = new FormData();
fd.append("name", "wang");
fd.append("age", 18);
var content = '<a id="a"><b id="b">hey!</b></a>';
var blob = new Blob([content], { type: "text/xml"});
fd.append("webmasterfile", blob);
$.ajax({
url: 'http://localhost:8080/test',
type: 'POST',
contentType:false,
data:fd,
processData:false
});
参考: