Jquery-Ajax-“Uncaught TypeError: Illegal invocation”错误

先看下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文档关于processDatacontentType 参数解释,

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
});

参考:

http://api.jquery.com/jQuery.ajax/

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值