表单序列化

传统提交表单是submit将表单提交到服务器端,如果使用Ajax的话,需要先获取每一个表单元素,太麻烦,所以用到表单序列化

<body>
    <!--<input type="button" value="Ajax" />-->
    
    <form>
        用户名:<input type="text" name="user" />
        邮件:<input type="email" name="email" />
        <input type="radio" name="sex" value="男" />
        <input type="radio" name="sex" value="女" />
        <input type="button" value="提交" />
    </form>
    <div id="box"></div>
    
</body>

常规:

    $('form input[type=button]').click(function(){
        $.ajax({
            type:"post",
            url:"test.php",
            async:true,
            data:{//需要一个一个获取,效率低下
                email:$('form input[type=email]').val(),
                user:$('form input[type=text]').val(),
            },
            success:function(response,status,xhr){
                $('#box').html(response);
            }
        });
    });

序列化方法:

    $('form input[type=button]').click(function(){
        $.ajax({
            type:"post",
            url:"test.php",
            async:true,
            data:$('form').serialize(),
            success:function(response,status,xhr){
                $('#box').html(response);
            }
        });
    });

 

    //不但可以序列化表单,还可以直接获取单选复选下拉内容
    $('form input[name=sex]').click(function(){
        $('#box').html(decodeURIComponent($(this).serialize()));
    });
    
    $('form input[name=sex]').click(function(){
        var json = $(this).serializeArray();
        $('#box').html(json[0].name +'='+ json[0].value);
    });
    
    //多次使用$.ajax(),每次初始化很麻烦,所以可以统一初始化
    $.ajaxSetup({
        type:'post',
        url:'test.php',
        data:$('form').serialize()
    });
    $('form input[type=button]').click(function(){
        $.ajax({
            success:function(response,status,xhr){
                $('#box').html(response);
            }
        });
    });
    
    //以对象形式传递键值对程序对于复杂的可能解析能力有限,故可以将其转换为字符串格式进行传递
    $('form input[type=button]').click(function(){
        $.ajax({
            type:"post",
            url:"test.php",
            async:true,
            data:{
                email:$('form input[type=email]').val(),
                user:$('form input[type=text]').val()
            },
            success:function(response,status,xhr){
                $('#box').html(response);
            }
        });
    });

 

posted @ 2017-02-13 09:31  党兴明  阅读(223)  评论(0编辑  收藏  举报