jquery 序列化表单 serialize(ajax提交表单)

将表单序列化

$('#yourformid').serialize()

例子

html页面

<form id="myform">
    登录名:<input type="text" name="username" value="李雷"><br>
    密码:<input type="text" name="password" value="123456"><br>
    性别:<input type="radio" name="sex" value="0" >女&nbsp;&nbsp;
    <input type="radio" name="sex" value="1" checked>男&nbsp;&nbsp;<br>
    爱好:<input type="checkbox" value="wzry" name="like">王者荣耀&nbsp;&nbsp;
    <input type="checkbox" value="cj" name="like" checked>吃鸡&nbsp;&nbsp;
    <input type="checkbox" value="douyin" name="like" checked>抖音&nbsp;&nbsp;<br>

    民族:
    <select name="minzu">
        <option value="-1" >--请选择--</option>
        <option value="1" >汉族</option>
        <option value="2" selected>满族</option>
        <option value="3" >蒙古族</option>
    </select> <br>
    描述:<textarea name="descrip"></textarea><br>
    <input type="button" value="注册" id="reg">
</form>

序列化:

console.log(  $("#myform").serialize()  );

输出结果:

username=%E6%9D%8E%E9%9B%B7&password=123456&sex=1&like=cj&like=douyin&minzu=2&descrip=

相当于 url 传参数

将表单序列化后,ajax提交

$.ajax({
    cache: true,//布尔值,表示浏览器是否缓存被请求页面。默认是 true。
    type: "POST",//请求类型
    url:ajaxCallUrl,
    data:$('#yourformid').serialize(),// 你的formid
    async: true,//是否异步处理,默认是true
    dataType:"json",//预设服务器返回来的数据类型
    success: function(data) {
        //成功时处理的代码
    },
    error: function(request) {
        alert('发生错误')
        console.log(xhr.responseJSON) // json格式,ajax请求使用该对象
    }
});