I'm using jQuery and Ajax for my forms to submit data and files but I'm not sure how to send both data and files in one form?(我正在为表单使用jQuery和Ajax来提交数据和文件,但是我不确定如何以一种形式发送数据和文件?)
I currently do almost the same with both methods but the way in which the data is gathered into an array is different, the data uses .serialize();
(我目前对这两种方法几乎相同,但是将数据收集到数组中的方式不同,数据使用.serialize();
) but the files use = new FormData($(this)[0]);
(但是文件使用= new FormData($(this)[0]);
)
Is it possible to combine both methods to be able to upload files and data in one form through Ajax?(是否可以将两种方法结合起来以通过Ajax以一种形式上载文件和数据?)
Data jQuery, Ajax and html(数据jQuery,Ajax和html)
$("form#data").submit(function(){
var formData = $(this).serialize();
$.ajax({
url: window.location.pathname,
type: 'POST',
data: formData,
async: false,
success: function (data) {
alert(data)
},
cache: false,
contentType: false,
processData: false
});
return false;
});
<form id="data" method="post">
<input type="text" name="first" value="Bob" />
<input type="text" name="middle" value="James" />
<input type="text" name="last" value="Smith" />
<button>Submit</button>
</form>
Files jQuery, Ajax and html(文件jQuery,Ajax和html)
$("form#files").submit(function(){
var formData = new FormData($(this)[0]);
$.ajax({
url: window.location.pathname,
type: 'POST',
data: formData,
async: false,
success: function (data) {
alert(data)
},
cache: false,
contentType: false,
processData: false
});
return false;
});
<form id="files" method="post" enctype="multipart/form-data">
<input name="image" type="file" />
<button>Submit</button>
</form>
How can I combine the above so that I can send data and files in one form via Ajax?(如何结合以上内容,以便可以通过Ajax以一种形式发送数据和文件?)
My aim is to be able to send all of this form in one post with Ajax, is it possible?(我的目标是能够通过Ajax在一个帖子中发送所有此表格,这可能吗?)
<form id="datafiles" method="post" enctype="multipart/form-data">
<input type="text" name="first" value="Bob" />
<input type="text" name="middle" value="James" />
<input type="text" name="last" value="Smith" />
<input name="image" type="file" />
<button>Submit</button>
</form>
ask by Dan translate from so
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…