zoukankan      html  css  js  c++  java
  • 表单序列化

    传统提交表单是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);
                }
            });
        });
  • 相关阅读:
    MySQL表的完整性约束
    MySQL支持的数据类型
    MySQL表操作
    MySQL存储引擎概述
    onblur和onkeyup事件
    Web控件LinkButton
    jQuery防止中文乱码
    jQuery 动态添加、删除css样式
    VS2012生成Web时报未能找到元数据文件xxx.dll
    单击EasyUI的datagrid行时不选中
  • 原文地址:https://www.cnblogs.com/by-dxm/p/6392513.html
Copyright © 2011-2022 走看看