<form action="javascript:;" onsubmit="return add_goods();" id="add_goods" method="post" enctype="multipart/form-data" >
<div class="form-group">
<label for="g_image">商品图片</label>
<div class="input-group">
<div class="custom-file">
<input type="file" class="custom-file-input" name="g_image" id="g_image">
<label class="custom-file-label" for="g_image">选择图片</label>
</div>
<div class="input-group-append">
<span class="input-group-text">上传</span>
</div>
</div>
</div>
</form>
function add_goods() {
var _form = $('#add_goods');
var data = _form.serializeArray(); // 批量获取input的字段
console.log(data)
//图片获取
var files = $('#g_image')[0].files
var formData = new FormData(); //新建⼀个formData对象
formData.append("file", files[0]); //append()⽅法添加字段
$.each(data, function(k, v) {
formData.append(v.name,v.value)
})
$.ajax({
url: "/admin/add_goods",
data: formData,
type: 'post',
processData:false,//必填 必须false 才会避开jq对formdata的默认处理 XMLHttpRequest才会对formdata进⾏正确处理 否则会报Illegal invocation错误
contentType:false,//必填 必须false 才会加上正确的Content-Type
success: function (res) {
console.log(res);
var json = $.parseJSON(res)
Swal.fire(json.msg)
}})
}
本文为Larwas原创文章,转载无需和我联系,但请注明来自larwas博客 https://larwas.com
最新评论