在使用ajax进行文件上传的提交请求时会十分麻烦,于是发现了jquery.form.js插件
下载地址:https://www.bootcdn.cn/jquery.form/
做的是一个动态轮播图的demo,可供大家参考
另外使用轮播图插件swiper的帖子在这里:
https://blog.csdn.net/weixin_44253204/article/details/104199887
1.HTML
注意添加enctype="multipart/form-data"
!
注意input控件的name
要和后端参数一致!
<!-- form表单-->
<form action="" id="uploadForm" method="post" enctype="multipart/form-data" class="form-horizontal" role="form"
οnsubmit="document.charset='UTF-8'">
<div class="form-group col-lg-7">
<label for="img_title">图片标题</label>
<input id="img_title" name="title" type="text" class="form-control">
<!-- 文件控件在这里 -->
<label for="img_Url">图片Url</label>
<input id="img_Url" name="fileObj" type="file" class="form-control">
<label for="target_Url">目标Url</label>
<input id="target_Url" name="targetUrl" type="text" class="form-control">
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<!-- 提交按钮在这里 -->
<button type="button" class="btn btn-primary" id="save_btn">Save</button>
</div>
2.js
/*
提交按钮单价事件
使用jquery.from插件上传文件
*/
$("#save_btn").click(function() {
var option = {//请求属性及回调函数
url: 'http://localhost:80/controller/slide/addslide',
type: 'POST',
dataType: 'json',
headers: {
"ClientCallMode": "ajax"
}, //添加请求头部
success: function(data) {
alert(data.msg);
//bootstrap的模态框隐藏
$("#updateFrom").modal('hide');
},
error: function(data) {
alert("上传失败,请联系管理员!");
}
};
//传入参数,执行submit
$("#uploadForm").ajaxSubmit(option);
return false; //最好返回false,因为如果按钮类型是submit,则表单自己又会提交一次;返回false阻止表单再次提交
});