# Ajax Submit File 遇到的問題 ###### tags: `被玩壞了` ## 原本是用 jquery 序列化 他不會序列化出 input file 就是說 Post 出去的 **Form Data 完全不會有 input file 的資料** ``` form.serialized() ``` --- ## 為了 input file,改用 FormData ``` var form = $(options.submitFormSelector); var data = new FormData(form[0]); // 查看 FormData 的資料,Display the key/value pairs for (var pair of data.entries()) { console.log(pair[0] + ', ' + pair[1]); } ``` --- ## 為什麼出現 Illegal invocation !! --> 資料問題 ### Ajax Option -> processData #### ★ processData 預設為 true,processData 為 true 會序列化成 query string 大概長這樣 ( keyA=value&keyB=value.... ) ↓↓↓ ``` __RequestVerificationToken=fHjQILzFMUTgG2NF8mQoNeRkS66gXLZmjR-dTxnQKJ3YbkOG1nGwT_eQ8fpmDFqCGOXoZ96qZsQjWHLgPCK_OYnNhZSFZNGG72gWxCw8KhU1&CreateTime=2020%2F9%2F3%20%E4%B8%8B%E5%8D%88%2005%3A46%3A00&Code=&Display=&IsEnabled=true&IsEnabled=false&Memo= ``` #### ★ processData 設為 false 時,禁止此自動轉換。物件型式則為 Key/Value pairs,正是 Model Binding 需要滴~ --- ## 為什麼 沒有出現 Illegal invocation 還是沒有成功 post file --> 表頭問題 ### Ajax Option -> contentType contentType 預設為 application/x-www-form-urlencoded,但是因為 Form 要 Post File 回去,需要使用 multipart/form-data #### ★ contentType : false,禁止 Ajax 加入 Content-Type  --- ## 完整的 Code ~ ``` // Submit 按鈕的事件 ( Ajax Submit ) $("#FormModal #FormModal_btnSubmit").off("click").on("click", function (e) { var form = $(options.submitFormSelector); //var form = document.querySelector(options.submitFormSelector); var url = form.attr('action'); var data = new FormData(form[0]); // 查看 FormData 的資料,Display the key/value pairs for (var pair of data.entries()) { console.log(pair[0] + ', ' + pair[1]); } $.ajax({ type: "POST", url: url, data: data, //form.serialize(), // serializes the form's elements. dataType: "json", processData: false, //傳送至 Server 的資料,會自動轉為 query string 的型式,如果是 GET 請求還會幫你附加到 URL。可用 processData 選項禁止此自動轉換。物件型式則為 Key/Value pairs contentType: false, // contentType 選項設置為 false,強制 jQuery 不加入 Content-Type 頭 success: function (result) { if (result.Status == "@ExamLibrary.Enums.EResultStatus.Success.ToString("d")") { $("#FormModal").modal("hide"); isComplete = true; } if (result.Status == "@ExamLibrary.Enums.EResultStatus.InvalidDataReturnView.ToString("d")") { if (result.FailMessage != null && result.FailMessage != "") { modalAlert({ content: result.FailMessage }); } $("#FormModal .modal-body").empty(); $("#FormModal .modal-body").html(result.Data); } }// success: function (result) { });// $.ajax({ e.preventDefault(); // avoid to execute the actual submit of the form. }); ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up