form表单提交转为ajax方式提交
在做项目的过程中遇到要将form表单提交转为ajax方式提交,下面是我总结的如何把form表单提交无缝转为ajax方式提交的方法。
原先的form表单长这样:
<form action="xxx" method="get"> //action的值是请求的url地址
<div class="form-group">
<label for="name">姓名</label>
<input type="text" class="form-control" name="name">
</div>
<div class="form-group">
<label for="jobNumber">工号</label>
<input type="number" class="form-control" name="jobNumber">
</div>
<div class="form-group">
<label for="nation">民族</label>
<input type="text" class="form-control" name="nation">
</div>
<div class="form-group">
<label for="gender">性别</label>
<input type="text" class="form-control" name="gender">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">提交</button>
</div>
</form>要转化为ajax方式提交,需要做以下几个改变:
1. 将form元素的属性action和method去掉,添加id="myForm",form元素就变为<form id="myForm">
2. 将提交按钮的button的type="submit"改为type="button"
3. 在js文件中写入
$(function(){
$.ajax({
type : "GET",
url : "xxx",
success : function (data) {
console.log(data); //data即为后台返回的数据
}
});这样,就可以愉快地将form表单提交的方式转为ajax请求的方式啦。
PS:如果想要在ajax请求中加入自定义的HTTP header,则在ajax请求中加入
beforeSend: function(request) {
request.setRequestHeader("Content-type", "application/json");
//通过这种方法可以设置自定义HTTP头字段
}, 相关推荐
wcqwcq 2020-07-04
TONIYH 2020-06-11
kentrl 2020-11-10
结束数据方法的参数,该如何定义?-- 集合为自定义实体类中的结合属性,有几个实体类,改变下标就行了。<input id="add" type="button" value="新增visitor&quo
ajaxyan 2020-11-09
zndy0 2020-11-03
学留痕 2020-09-20
learningever 2020-09-19
chongxiaocheng 2020-08-16
ajaxhe 2020-08-16
lyqdanang 2020-08-16
curiousL 2020-08-03
时光如瑾雨微凉 2020-07-19
坚持着执着 2020-07-16
jiaguoquan00 2020-07-07