我不確定這個問題是否值得問,但我似乎無法找到解決方法,所以在這裏。在將它傳遞給一個新函數後使用FormData
我有一個Flask應用程序,我在其中提交了一個將圖像上傳到服務器的表單。我送使用創建這樣FORMDATA圖像:
$("#myform").submit(function(event) {
event.preventDefault();
var $form = $(this),
formObject = $('form')[0],
formData = new FormData(formObject);
// other stuff
的FORMDATA然後通過一個AJAX POST請求到服務器發送。當POST請求位於submit函數中時,此操作完美工作。
問題是,在其他視圖中,我需要使用相同的代碼,但我將AJAX POST請求從提交函數中移出。因此,當我將formObject
或formData
傳遞給包含AJAX請求的函數時,我們將其稱爲fctA
,它們未定義。
我認爲我看到了問題,因爲提交功能有一個「特定狀態」(因爲您可以使用$(this)
獲取表格),但我找不到一種方法將formData
傳遞給其他函數。我不想擺脫fctA
,因爲它可以避免複製大量代碼(因爲客戶端驗證)
有沒有辦法通過不同的函數調用傳遞FormData?
在此先感謝。
//Edit: Here's the code where I want to pass the FormData
//(I'm having trouble indenting it here)
$.ajax({
url: "url",
type: "GET",
dataType: "json",
success: function(data) {
//Create a JSON object to send other form inputs
/*
fctA is used to avoid duplicating AJAX POST requests since I
need to send the data only when meeting some expectations and
I must display error messages otherwise.
*/
fctA(json, formObject)
/*
The image is correctly sent if I have a POST request that
uses formData right here instead of passing it to fctA.
As soon as the POST request leaves the submit function to go to fctA though,
formData is undefined when I execute the code.
I tried passing formObject or formData, they are both undefined.
*/
},
error: function() {
//Display an error message
}
});
我沒有看到傳遞formData的問題。你可以請張貼相關的代碼? – mm759
@ mm759我已經用ajax調用更新了問題,我在其中使用formData。 – Batman