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

太过爱你忘了你带给我的痛 2022-05-09 04:34 383阅读 0赞

先看下ajax请求:

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="UTF-8">
  5. <title></title>
  6. </head>
  7. <body>
  8. </body>
  9. <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
  10. <script>
  11. var fd = new FormData();
  12. fd.append("name", "wang");
  13. $.ajax({
  14. url: 'http://localhost:8080/test',
  15. type: 'POST',
  16. data:fd,
  17. //processData:false
  18. });
  19. </script>
  20. </html>

此时ajax请求并不成功,会报【TypeError: Illegal invocation】错误
在这里插入图片描述
再看下Jquery关于Ajax方法的doc文档关于processDatacontentType 参数解释,

  1. processData (default: true)
  2. Type: Boolean
  3. 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。

  1. contentType (default: 'application/x-www-form-urlencoded; charset=UTF-8')
  2. Type: Boolean or String
  3. 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正确设置:

  1. var fd = new FormData();
  2. fd.append("name", "wang");
  3. fd.append("age", 18);
  4. var content = '<a id="a"><b id="b">hey!</b></a>';
  5. var blob = new Blob([content], { type: "text/xml"});
  6. fd.append("webmasterfile", blob);
  7. $.ajax({
  8. url: 'http://localhost:8080/test',
  9. type: 'POST',
  10. contentType:false,
  11. data:fd,
  12. processData:false
  13. });

参考:

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

发表评论

表情:
评论列表 (有 0 条评论,383人围观)

还没有评论,来说两句吧...

相关阅读