收集表单数据——获取打包的表单数据4
程序员文章站
2022-05-29 23:12:41
...
前言:form表单外部额外增加表单元素,最后一起打包数据,发送请求
实现原理,往自定义formdata的空对象中不断添加数据,以达到请求接口需要的参数
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
<style>
.formbox{
box-shadow: #DDD 1px 1px 4px;
margin: 20px;
}
form{
display: inline-block;
border: 1px solid red;
margin-right: 50px;
}
.selbox{
display: inline-block;
vertical-align: top;
}
.sub{
display: inline-block;
width: 166px;
height: 50px;
line-height: 50px;
text-align: center;
background: #ff9400;
color: #fff;
margin: 20px;
}
</style>
</head>
<body>
<div class="formbox">
<form id="div1">
<h2>表单内容</h2>
性别:<input type="text" name="sex" value="男"/><br />
年龄:<input type="text" name="age" value="18"/><br />
地址:<input type="text" name="where" value="四川"/><br />
电话:<input type="text" name="phone" value="1588114..."/><br />
政治面貌:<select name="politics">
<option value="1">群众</option>
<option value="2">团员</option>
<option value="3">党员</option>
</select>
</form>
<div class="selbox">
<b>城市:</b>
<select name="city">
<option value="成都">成都</option>
<option value="重庆">重庆</option>
<option value="*">*</option>
</select>
<br />
<b>口味:</b>
<select name="choose">
<option value="活泼">活泼</option>
<option value="火辣">火辣</option>
<option value="闷骚">闷骚</option>
</select>
</div>
<br />
<span class="sub jssub">提交</span>
</div>
<script src="jquery.min.js"></script>
<script>
$.fn.extend({
kuozhan:function(){
var data={};
$(this).serializeArray().map(function(x){data[x.name]=x.value});
return data;
}
});
var formdata = {};
$("body").on("click",".jssub",function(){
var gdata = $('#div1').kuozhan();
for(k in gdata){
formdata[k] = gdata[k];
}
ajax();
})
$("select[name='city']").change(function(){
formdata.city=$(this).val();
ajax();
});
$("select[name='choose']").change(function(){
formdata.choose=$(this).val();
ajax();
});
function ajax(){
console.log(formdata);
}
</script>
</body>
</html>