我不确定这个问题是否值得问,但我似乎无法找到解决方法,所以在这里。在将它传递给一个新函数后使用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