快速获取表单中的数据

1.serialize()函数

为了简化表单中数据的获取操作,jQuery提供了serialize()函数,其语法格式如下:

$(selector).serialize()

 好处:可以一次性获取到表单中的所有数据

注意:在使用serialize()函数快速获取表单数据时,必须为每个表单元素添加name属性!

示例:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="/form表单/jquery-3.6.0.js"></script>
</head>

<body>
    <form action="/login" id="f1">
        <input type="text" name="user_name">
        <input type="password" name="password">
        <button type="submit">提交</button>
    </form>
</body>
<script>
    $(function () {
        // 第一种方式
        // $('#f1').submit(function (e) {
        //     e.preventDefault()
        //     var data = $(this).serialize()
        //     console.log(data);
        // })

        // 第二种方式
        $('#f1').on('submit', function (e) {
            var data = $('#f1').serialize()
            e.preventDefault()
            console.log(data);
        })

    })
</script>

</html>

 

posted @ 2022-04-28 21:05  今天穿秋裤了吗  阅读(356)  评论(0)    收藏  举报