$(document).delegate('form', 'submit', function(event) {
var $form = $(this);
var id = $form.attr('id');
// ...
/* stop form from submitting normally */
event.preventDefault();
// /* get the action attribute from the <form action=""> element */
var $form = $(this),
url = $form.attr( 'action' );
var timeId = parseInt(id.substring(11));
var formData = new FormData($("#"+id)[0]);
console.log("time id of form is "+timeId);
console.log(formData);
$.ajax({
url: url,
method: "POST",
dataType: 'json',
data: formData,
processData: false,
contentType: false,
success: function(result){},
error: function(er){}
});
});
我发送的图像文件从一个html表单使用ajax post。如何将附加数据作为此http post的正文发送?
发布于 2016-09-27 16:04:29
要从DOM元素传递额外的数据,也可以使用serialize()
。
$('form#id').serialize();
如果你想得到图像,你应该这样做。
console.log($('#image').get(0).files[0]);
<input type="file" name="file" accept="image/*" id="image">
可以使用每个文件追加多个文件
var data = new FormData();
$.each($('#image')[0].files, function(i, file) {
data.append('file-'+i, file);
});
在formData中传递加法数据
data.append("timeId",10000);
//Program a custom submit function for the form
$("form#test").submit(function(event){
//disable the default form submission
event.preventDefault();
//Other data
console.log($(this).serialize());
//File data
console.log($('#image').get(0).files);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form enctype="multipart/form-data" id="test" method="post">
<input type="text" name="firstname">
<input type="text" name="lastname">
<input type="hidden" name="id" value="10">
<input type="file" name="file" id="image">
<input type="submit">
</form>
https://stackoverflow.com/questions/39719269
复制相似问题