Jquery-Ajax-“Uncaught TypeError: Illegal invocation”錯誤
阿新 • • 發佈:2018-12-12
先看下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
});
參考: