【发布时间】:2015-04-26 12:32:23
【问题描述】:
我正在尝试使用 AJAX 单独上传文件和其他表单数据。在这里,我关注this bootstrap 和 jquery 插件。
我可以在不上传文件的情况下解决这个问题,但我想用我的表单上传一个文件。
我是这样尝试的:
.on('success.form.fv', function(e) {
// Save the form data via an Ajax request
e.preventDefault();
var $form = $(e.target),
formData = new FormData(),
params = $form.serializeArray(),
files = $form.find('[name="new_product_image"]')[0].files,
id = $form.find('[name="product_id"]').val();
// The url and method might be different in your application
$.ajax({
url: './includes/process_edit_products.php',
method: 'POST',
//data: $form.serialize()
data: formData,
cache: false,
contentType: false,
processData: false,
}).success(function(response) {
response = jQuery.parseJSON(response);
// Get the cells
var $button = $('button[data-id="' + response.product_id + '"]'),
$tr = $button.closest('tr'),
$cells = $tr.find('td');
// Update the cell data
$cells
.eq(0).html(response.product_name).end()
.eq(1).html(response.price).end()
.eq(2).html(response.product_des).end();
// Hide the dialog
$form.parents('.bootbox').modal('hide');
// You can inform the user that the data is updated successfully
// by highlighting the row or showing a message box
bootbox.alert('The product is updated successfully.');
});
});
更新:这是我的 HTML:
<form id="userForm" method="post" class="form-horizontal" enctype="multipart/form-data" style="display: none;">
<div class="form-group">
<label class="control-label" style="width:32%;">ID</label>
<div class="col-xs-3">
<input type="text" class="form-control" name="product_id" readonly />
</div>
</div>
<div class="form-group">
<label class="control-label" style="width:32%;">Product Name:</label>
<div class="col-xs-5">
<input type="text" class="form-control" name="product_name" />
</div>
</div>
<div class="form-group">
<label class="control-label" style="width:32%;">Product Price</label>
<div class="col-xs-5">
<input type="text" class="form-control" name="product_price" />
</div>
</div>
<div class="form-group">
<label class="control-label" style="width:32%;">Product Description</label>
<div class="col-xs-5">
<input type="text" class="form-control" name="product_des" />
</div>
</div>
<div class="form-group">
<label class="control-label" style="width:32%;">New Product Image:</label>
<div class="col-xs-5">
<input type="file" size="32" name="new_product_image">
<p class="help-block">*Only for jpg, gif and PNG files.</p>
</div>
</div>
<div class="form-group">
<div class="col-xs-5 col-xs-offset-4">
<button type="submit" class="btn btn-primary">Update Product</button>
</div>
</div>
</form>
谁能告诉我哪里出错了。任何帮助将不胜感激。
谢谢。
【问题讨论】:
-
你能显示你的html吗?
-
您不需要将参数和文件变量附加到 formData 中吗?就像他们在示例中所做的那样? formvalidation.io/examples/ajax-submit/…
-
@SaidKholov,我用我的 HTML 更新了我的问题
-
@MarcusHenrique,我不确定你问了什么......我错过了什么吗?
-
如果你
console.log(formData)你会得到什么
标签: javascript php jquery ajax twitter-bootstrap