zoukankan      html  css  js  c++  java
  • jQuery序列化表单数据 serialize()、serializeArray()及使用

    1、serialize() 方法:
      serialize() 方法通过序列化表单值,创建 URL 编码文本字符串

      您可以选择一个或多个表单元素(比如 input 及/或 文本框),或者 form 元素本身。

      序列化的值可在生成 AJAX 请求时用于 URL 查询字符串中,这样在ajax提交表单数据时,就不用一一列举每一个参数,只需将data参数设置为:$("form").serialize()即可。

    //语法
    $(selector).serialize()

      输出标准的查询字符串:a=1&b=2&c=3&d=4&e=5

      注释:只会将“成功的控件”序列化为字符串。(即指没被禁用的元素)如果不使用按钮来提交表单,则不对提交按钮的值序列化。如果要表单元素的值包含到序列字符串中,元素必须使用 name 属性。

    2、serializeArray() 方法
      serializeArray() 方法通过序列化表单值来创建对象数组(名称和值)
      您可以选择一个或多个表单元素(比如 input 及/或 textarea),或者 form 元素本身。
    //格式:
    var jsonData = $("form").serializeArray();
      注意:此方法返回的是 JSON 对象而非 JSON 字符串
      返回的 JSON 对象是由一个对象数组组成的,其中每个对象包含一个或两个名值对 —— name 参数和 value 参数(如果 value 不为空的话)。举例来说:
    [ 
      {name: 'firstname', value: 'Hello'}, 
      {name: 'lastname', value: 'World'},
      {name: 'alias'}, // 值为空
    ]
      特别说明,元素不能被禁用(禁用的元素不会被包括在内),并且元素应当有含有 name 属性。提交按钮的值也不会被序列化。文件选择元素的数据也不会被序列化。
      注意:1、不被禁用;2、包含name属性
    3、高级搜索实例:
      结构:
    <div class="title-search advanced_search"><table><tr><td>
        <div class="ui-filter">
            <div class="ui-filter-text " >
                <span><s:text name="cems.advancedSearch"></s:text></span>
            </div>
            <div class="ui-filter-list">
                <form id="hForm"  class="form">
                <table class="form">
                <tr>
                    <td class="formTitle"><s:text name="sys.column.name.unRegDevice.name"></s:text></td>
                    <td class="formValue" colspan="2">
                        <input id="unRegDevice_hostName" name="queryBean.hostName"  type="text"  class="form-control" placeholder='<s:text name="sys.column.name.unRegDevice.name"/>'   />
                    </td>            
                    <td class="formTitle"><s:text name="sys.column.name.unRegDevice.ip"></s:text></td>
                    <td class="formValue" colspan="2">
                        <input id="unRegDevice_ip" name="queryBean.ip"  type="text"  class="form-control" placeholder='<s:text name="sys.column.name.unRegDevice.ip"></s:text>'  data-mask=""  data-inputmask="'alias': 'ip'"   isvalid="yes" />
                    </td>
                </tr>
                <tr>
                    <td class="formTitle"><s:text name="sys.column.name.unRegDevice.groupName"></s:text></td>
                    <td class="formValue" colspan="2">
                        <input id="unRegDevice_groupName" name="queryBean.groupName"  type="text"  class="form-control" placeholder='<s:text name="sys.column.name.unRegDevice.groupName"></s:text>'   />
                    </td>             
                    <td class="formTitle"><s:text name="sys.column.name.unRegDevice.mac"></s:text></td>
                    <td class="formValue" colspan="2">
                        <input id="unRegDevice_mac" name="queryBean.mac"  type="text"  class="form-control" placeholder='<s:text name="sys.column.name.unRegDevice.mac"></s:text>'  isvalid="yes" />
                    </td> 
                </tr>
                <tr>
                    <td class="formTitle"><s:text name="sys.column.name.unRegDevice.updateTime"></s:text></td>
                    <td class="formValue" colspan="2">
                        <input id="Category" type="hidden" value="1" />
                        <div style="float: left;  45%;">
                            <input id="StartTime"   name="queryBean.updateBeginTime" readonly type="text"  class="form-control input-wdatepicker"  onclick="WdatePicker()"  onfocus="WdatePicker()">
                        </div>
                    </td>
                    <td class="formTitle">至</td>
                    <td class="formValue" colspan="2">
                        <div style="130px;">
                            <input id="EndTime"  name="queryBean.updateEndTime" readonly type="text"  class="form-control input-wdatepicker"   onclick="WdatePicker()"   onfocus="WdatePicker()">
                        </div>
                   </td> 
                </tr>
                <tr>
                    <td class="formTitle"><s:text name="sys.column.name.unRegDevice.isOpened"></s:text></td>
                    <td class="formValue" colspan="2">
                         <input type="radio" id="queryBean_isOpened" name="queryBean.isOpened" checked="checked" value="0" ></input>&nbsp;<s:text name="sys.column.name.unRegDevice.noStart"/>
                        <input type="radio" id="queryBean_isOpened1" name="queryBean.isOpened" value="1" ></input>&nbsp;<s:text name="sys.column.name.unRegDevice.start"/>
                    </td>              
                    <td class="formTitle"><s:text name="sys.column.name.unRegDevice.protectState"></s:text></td>
                    <td class="formValue" colspan="2">
                        <input type="radio" id="queryBean_protectState" checked="checked" name="queryBean.protectState" value="0" ></input>&nbsp;<s:text name="sys.column.name.unRegDevice.noProtect"/>
                        <input type="radio" id="queryBean_protectState1" name="queryBean.protectState" value="1" ></input>&nbsp;<s:text name="sys.column.name.unRegDevice.protect"/>
                    </td>
                </tr>
                <tr>
                    <td class="formTitle"><s:text name="sys.column.name.unRegDevice.isFireWall"></s:text></td>
                    <td class="formValue" colspan="5">
                        <input type="radio" name="queryBean.isFireWall" checked="checked" value="0"></input>&nbsp;<s:text name="sys.column.name.unRegDevice.noOpen"/>
                        <input type="radio" name="queryBean.isFireWall" value="1"></input>&nbsp;<s:text name="sys.column.name.unRegDevice.open"/>
                        <input type="radio" name="queryBean.isFireWall" value="2"></input>&nbsp;<s:text name="sys.column.name.unRegDevice.unknown"/>
                    </td>
                </tr>
                </table>
                </form>
                <div class="ui-filter-list-bottom">
                    <a id="btn_Reset" class="btn btn-default"><s:text name="cems.clear"></s:text></a>
                    <a id="highSearchButton" class="btn btn-primary"><s:text name="cems.ok"></s:text></a>
                   </div>
               </div>
        </div>
    </td></tr></table></div>

      高级搜索执行:

    /****高级搜索执行***/
    $("#highSearchButton").bind("click",function(){
        if($("#hForm").Validform()){
        if (!$(".ui-filter-text").next('.ui-filter-list').is(":hidden")) {
            $(".ui-filter-text").trigger("click");
        }
        $gridTable.jqGrid('setGridParam', {
             postData: serializeObject($("#hForm")), page: 1
            }).trigger('reloadGrid');  
        }
    });

      序列号表单数据:

    /**
     *序列化form表单
     *@param  要序列化的表单的名称 
     *@return 返回对象
     ***/
    function serializeObject(form){
        var o = {};
        form.find(".ui-select").each(function(r){
          var name=$(this).attr("name");
          var value=$(this).attr("data-value");
          o[name]= value;
        })
        
        $.each(form.serializeArray(),function(index){
            if(o[this['name']]){
                o[this['name']] = o[this['name']] + ","+this['value'];
             }else{
                 o[this['name']] =  this['value'];
             }
        });
        return o;
    }

     

      form.serializeArray():通过序列化表单值来创建对象数组(名称和值);

      index:代表该对象数组的索引

       然后java action层:

    public class UnRegDeviceAction extends BaseActionImpl {
    ……
    //页面queryBean对象
    private UnRegDeviceQueryBean queryBean;
    //get/set方法
    public UnRegDeviceQueryBean getQueryBean() {
        return queryBean;
    }
    public void setQueryBean(UnRegDeviceQueryBean queryBean) {
        this.queryBean = queryBean;
    }
    ……
    }
    
                

      数据列表查询:

       /**
         * 数据列表查询
         */
        public void getDeviceJson(){
            log.info("未注册设备数据列表查询-ST");
            Page<UnRegDevice> page = null;
            List<UnRegDevice> dataList = null;
            //拼排序条件。
            log.info("拼排序条件-ST");
             String orderStr = getRequest().getParameter("order");
             String sortStr=  getRequest().getParameter("sort");
             if(queryBean == null){
                 queryBean = new UnRegDeviceQueryBean();
             }
             if(sortStr != null && orderStr != null){
                 String[] orderArr = orderStr.split(",");
                 String[] sortArr = sortStr.split(",");
                 for(int i=0;i<sortArr.length;i++){
                     queryBean.addOrderProperty("this."+sortArr[i], "asc".equals(orderArr[i]) ? Order.ASC : Order.DESC);
                 }
             }log.info("拼排序条件-END");
             
            //---------------------------------数据过滤ST
             log.info("数据过滤-ST");
                 @SuppressWarnings("unchecked")
                 Map<String, List<String>>  mgrOrgMap =  (Map<String, List<String>>) getSession().getAttribute(OrganizationUtil.ORG_MGR);
                  if(OrganizationUtil.isNullMgrOrg(mgrOrgMap)){
                      dataList = new ArrayList<UnRegDevice>();
                  }else{
                      Organization mgrOrg = new Organization();
                        mgrOrg.setMgrOrg(mgrOrgMap);
                        queryBean.setOrganization(mgrOrg);
                       page = unRegDeviceService.query(queryBean, getCurrentPageNo(), getPageSize());
                      dataList = page.getDataList();
                  }
                   log.info("数据过滤-END");
                 //---------------------------------数据过滤END
             
            JsonConfigEx jsonConfigEx = new JsonConfigEx();
            jsonConfigEx.addPropertyIncludes("organization","name");
            jsonConfigEx.setIgoreHibernateLazyLoadProperty(false);
            String json = JsonUtils.collection2Json(dataList,jsonConfigEx);
            /*** 组装成grirdJson格式 ***/
            int total = 0;
            if (page != null) {
                 String  ob = getSession().getAttribute("selectStyle").toString();
                    if("1".equals(ob)){
                        total = page.getTotalDataCount();
                    }else{
                        total = page.getTotalPageCount();
                                
                    }
            }
            String girdJson = EasyUIGridUtils.toGridJson(total, json);
            print(girdJson);
             log.info("未注册设备数据列表查询-END-数据格式:"+girdJson );
        }

      可以看到上面的queryBean查询条件:

      (1)当未高级搜索时,queryBean 为 null。

      (2)高级搜索时,queryBean 为传过来的值。

      bean内容

    package com.vrv.cems.assets.bean; 
    
    import java.sql.Timestamp;
    import java.util.ArrayList;
    import java.util.List;
    
    import com.sys.common.base.support.QueryObject;
    import com.sys.common.base.support.Orderable.Order;
    import com.sys.common.base.support.Orderable.OrderedProperty;
    import com.vrv.cems.assets.domain.UnRegDevice;
    
    public class UnRegDeviceQueryBean extends UnRegDevice {
        private static final long serialVersionUID = -8893630319158639345L;
        private List<String> organizationIds = new ArrayList<String>(); //组织机构ID
        //扫描数据入库开始时间
        private Timestamp updateBeginTime;
        private Timestamp updateEndTime;
        private boolean  orgIdIsEmpty;
        public boolean isOrgIdIsEmpty() {
            return orgIdIsEmpty;
        }
        public void setOrgIdIsEmpty(boolean orgIdIsEmpty) {
            this.orgIdIsEmpty = orgIdIsEmpty;
        }
        private String organizationName;//组织名称
        private String devType;//设备类型名称
        public String getDevType() {
            return devType;
        }
        public void setDevType(String devType) {
            this.devType = devType;
        }
        private String conditions;
        //扫描数据入库结束时间
        /**
         * 内部查询代理对象。
         */
        private QueryObject queryObject = new QueryObject();
        /**
         * 获取排序规则对象
         */
        public List<OrderedProperty> getOrderedProperties() {
            return queryObject.getOrderedProperties();
        }
        public void addOrderProperty(String propertyName, Order order) {
            queryObject.addOrderProperty(propertyName, order);
        }
    
        public void addOrderProperty(String propertyName) {
            queryObject.addOrderProperty(propertyName);
        }
        public Timestamp getUpdateBeginTime() {
            return updateBeginTime;
        }
        public void setUpdateBeginTime(Timestamp updateBeginTime) {
            this.updateBeginTime = updateBeginTime;
        }
        public Timestamp getUpdateEndTime() {
            return updateEndTime;
        }
        public void setUpdateEndTime(Timestamp updateEndTime) {
            this.updateEndTime = updateEndTime;
        }
        public List<String> getOrganizationIds() 
        {
            return organizationIds;
        }
        public void setOrganizationIds(List<String> organizationIds)
        {
            this.organizationIds = organizationIds;
        }
        
        
        public String getConditions() {
            return conditions;
        }
        public void setConditions(String conditions) {
            this.conditions = conditions;
        }
    
        public String getOrganizationName() {
            return organizationName;
        }
        public void setOrganizationName(String organizationName) {
            this.organizationName = organizationName;
        }
    }

     

  • 相关阅读:
    移动设备横竖屏判断 CSS 、JS
    Jquery监听value的变化
    设置了line-block的div会出现间隙
    移动端点击可点击元素时,出现蓝色默认背景色
    网页顶部进度条-NProcess.js
    ios UITableView
    ios UIScrollView
    ios Xcode 快捷方式
    ios常用方法、基础语法总结
    Mac eclipse Tomcat安装
  • 原文地址:https://www.cnblogs.com/goloving/p/7417577.html
Copyright © 2011-2022 走看看