应用场景: jquery + ajax 表单提交,一次性获取所有表单,并解析到post 参数
常用点 1 :
//获取所有表单参数: 结果格式为: a=1&b=2&c=3
$('form').serialize();
常用点 2 :jquery 解析 url参数
//封装方法
(function($) {
var re = /([^&=]+)=?([^&]*)/g,
decodeRE = /\+/g,
decode = function (str) { return decodeURIComponent( str.replace(decodeRE, " ") ); };
$.parseParams = function(query) {
let params = {}, e;
while ( e = re.exec(query) ) params[ decode(e[1]) ] = decode( e[2] );
return params;
};
})(jQuery);
//使用方法 :
var formdata = 'a=1&b=2&c=3';
var json_data = $.parseParams(formdata); //json_data 格式 : {a:1,b:2,c:3}
完整使用的示例代码
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=0,viewport-fit=cover">
<title>login</title>
<link rel="stylesheet" href="__CPLUGINS__/weui/css/weui.css" />
</head>
<body>
<div class="weui-form__control-area">
<div class="weui-form__text-area">
<h2 class="weui-form__title">login</h2>
</div>
<form method="post" >
<div class="weui-cells__group weui-cells__group_form">
<div class="weui-cells weui-cells_form">
<div class="weui-cell weui-cell_active">
<div class="weui-cell__hd"><label class="weui-label">用户名</label></div>
<div class="weui-cell__bd">
<input class="weui-input" name="user_name" placeholder="请输入"/>
</div>
</div>
<div class="weui-cell weui-cell_active">
<div class="weui-cell__hd"><label class="weui-label">密码</label></div>
<div class="weui-cell__bd">
<input class="weui-input" name="pass" placeholder="请输入" />
</div>
</div>
</div>
</div>
</form>
</div>
<div class="weui-form__opr-area">
<a class="weui-btn weui-btn_primary" href="javascript:" id='send' >确定</a>
</div>
</body>
<script type="text/javascript" src="__MJS__/jquery-2.1.0.js"></script>
<script>
//监听提交
$('#send').on('click', function () {
//获取所有的form表单参数
var alldata = $('form').serialize();
//此处调用下方的封装函数
form_param = $.parseParams(alldata);
//ajax请求
$.post("/reg_send", {
user_name: form_param.user_name,
pass: form_param.pass,
}, function (res) {
layer.msg(res.message)
if (res.status == 2) {
//成功
}
});
return false;
});
//解析参数: 此处是封装的函数,
(function($) {
var re = /([^&=]+)=?([^&]*)/g,
decodeRE = /\+/g,
decode = function (str) { return decodeURIComponent( str.replace(decodeRE, " ") ); };
$.parseParams = function(query) {
let params = {}, e;
while ( e = re.exec(query) ) params[ decode(e[1]) ] = decode( e[2] );
return params;
};
})(jQuery);
</script>
</html>