簡體   English   中英

Ajax文件上傳的奇怪問題(jQuery,ASP.Net MVC)

[英]Strange issue with Ajax file upload (jQuery, ASP.Net MVC)

在我的網站的幾個頁面(ASP.Net MVC,jQuery,KendoUI SPA)上,我有一個模式窗口來上傳文件。

 addAttachment: function (e) { $("form").on("submit", function (event) { event.preventDefault(); }); e.preventDefault(); var formData = new FormData($("#formUpload")[0]); var url = 'api/Attachments/UploadAttachment'; app.postFile(url, formData, function (statusCode) { if (statusCode === 201) { // File was created -- do stuff } }); }, 
 <div id="addAttachmentWindow" data-role="window" data-height="300px" data-width="600px" data-modal="true" data-title="Add Attachment" data-visible="false"> <div class="row"> <form id="formUpload" class="form-horizontal"> <input type="hidden" id="hdnRecordId" name="recordId" data-bind="value: object.id" /> <div class="form-group"> <label class="col-sm-4 control-label" for="txtDocumentTitle">Title</label> <div class="col-sm-6"> <input name="documentTitle" id="txtDocumentTitle" type="text" class="k-textbox" /> </div> </div> <div class="form-group"> <label class="col-sm-4 control-label" for="fuFileInput">Document</label> <div class="col-sm-6"> <input id="fuFileInput" name="files" type="file" /> </div> </div> <div class="col-sm-6 col-sm-offset-6"> <button data-role="button" data-icon="plus" data-bind="click: addAttachment">Add Attachment</button> </div> </form> </div> </div> 

帶有postFile的代碼

var postFile = function(uri, formData, callback) {
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
            callback(xhr.status);
        }
    };
    xhr.open('POST', uri);
    xhr.setRequestHeader("RequestVerificationToken", antiForgeryToken);
    xhr.send(formData);
};

大多數頁面都可以正常工作,但是在幾個頁面上,它將發布POST,而沒有表單字段,並立即為

/?recordId=1&documentTitle=documentTitleInput&files=FileNameHere.pdf

轉到本地控制器的索引功能。 如果我轉到有此問題的頁面之一,請執行Shift-Reload,然后嘗試上載,它將按預期工作,表單字段保持不變,並調用回調。

問題

  • 為什么在初始POST之后(甚至在POST返回響應之前)立即使用查詢字符串中的表單字段發出GET的原因
  • 為什么表單字段為空,除非我在某些頁面上執行shift-reload,而在其他頁面上使用相同的代碼卻能正常工作。

我嘗試創建一個空的FormData並將其值附加到其中,並播放了我發現的所有內容以阻止發生正常的提交事件( e.preventDefault()e.stopPropogation()return false等);

好的,所以請閱讀有關該主題的內容及其相關內容,因為prevent default僅適用於元素,而不適用於表單提交事件,這是您使用的...

創建兩個提交輸入...一個按鈕,另一個隱藏輸入..像這樣..

<button type="button" id="submit">Submit</button>
<input style="display: none;" type="submit" id="realsubmit">

然后像這樣做你的jQuery ...

$("#submit").on('click', function() {

  //do stuff
  $("#realsubmit").trigger('click');
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM