jquery Table DataTables instance parsing direct load and delay loading _jquery

Source: Internet
Author: User

Refer to the official documentation, you need to introduce jquery.js,jquery.datatables.js,datatables.bootstrap.js (optional),
Due to the tight time, omitted a lot, so the summary of the simplified version of the only reference.

1, direct loading , this relatively simple, as follows

<div id= "tid" class= "col-sm-12 col-md-12" >
  <div id= "Secondtid" hidden= "hidden" ></div>
</div>

JSP uses the bootstrap grid, JS is as follows

<script type= "Text/javascript" > Function Getgaoxinqu () {$ (' #secondtid '). Remove (); $ ("#tid"). Append ("<div id=" Secondtid ' style= ' width:100%; ') ><table id= ' table_id ' class= ' table table-striped table-bordered table-hover no-footer dataTable display ' >< thead><tr><th nowrap>id</th><th nowrap> High-tech zone name </th><th nowrap> area </th> <th nowrap> Industrial and commercial registered enterprises </th><th nowrap> Web site </th><th nowrap> Industry output value (Thousand) </th><th Nowrap> industrial Added value (thousand yuan) </th><th nowrap> leading industry </th><th nowrap> Revenue (million) </th><th nowrap
      > Financial expenditure (million) </th></tr></thead><tbody></tbody></table></div> "); 
            $.ajax ({url: ' ${contextpath}/mst/theme/otheroperateplatformtheme.do?flag=gaoxinqu ',//Jump to action Data: {barname: ' 1 '}, serverside:true,//server processing traditional:true
          ,  Type: ' Post ', success:function (data) {var dataobj = eval (data); $ (' #table_id ').
                        DataTable ({data:dataobj, sscrolly:600,
                        SSCROLLX: ' 100% ', columns: [{data: ' ID ' 
                        },{data: ' Name '}, {data: ' dy '
                          }, {data: ' Gxqyy '}, {
                          Data: ' www '}, {data: ' Gysum '}, {
                        Data: ' Gyadd '}, {data: ' Zdcy '
                     }, {data: ' Cztr '}, {data: ' CZZC '   }], order:[[0, "ASC"]], language: {Searc
                          H: "Search in the form:", Show: "Display", "sprocessing": "Processing ...",
                          "Slengthmenu": "Show _menu_ results", "szerorecords": "No Match results",
                          "Sinfo": "Show _start_ to _end_ results, total _total_ items", "Sinfoempty": "Display No. 0 to No. 0 results, total 0 items",
                          "Sinfofiltered": "(Filtered by _max_ results)", "Sinfopostfix": "",
                          "Ssearch": "Search:", "sURL": "", "semptytable": "The data in the table is empty",
                          "Sloadingrecords": "Load in ...", "sinfothousands": ",",
                            "Opaginate": {"Sfirst": "Home", "sprevious": "Prev", "Snext": Next Page", "Slast": "Last"}, "Oaria": {
                          ' Ssortascending: ': Arrange this column in ascending order, ' ssortdescending: ': Arrange this column in descending order
              }
                        }
                      });
            ShowPage (); }, Error:function () {alert ("Exception!)"
            ");
      }
          });

 ShowPage ()//Height adjustment} </script>

The background to pass a JSON on the line, because this broken project table name is very wonderful to see it.

List<gaoxindistrict> gxlist=new arraylist<gaoxindistrict> ();
      String sql= "SELECT * from ODS10000060";
        try {list<map> List = oracledictionaryservice.executesqltorecordmap (sql);
          for (Map map:list) {gaoxindistrict gx=new gaoxindistrict ();
          Object id= map.get ("id");
          Object name = Map.get ("name");
          Object JB = map.get ("JB");
          Object DY = map.get ("dy");
          Object year = Map.get ("year");
          Object FZR = Map.get ("FZR");
          Object TBR = Map.get ("TBR");
          Object phone = map.get ("Phone");
          Object email = map.get ("email");
          Object www = map.get ("www");
          Object gxqmjsum = Map.get ("Gxqmjsum");
          Object JCMJ = Map.get ("JCMJ");
          Object gxqyy = Map.get ("Gxqyy");
          Object gysum = Map.get ("Gysum");
          Object Gyadd = Map.get ("Gyadd");
          Object Cztr = Map.get ("Cztr");
        Object CZZC = Map.get ("Czzc");  Object Dec = map.get ("Dec");

          Object zdcy = Map.get ("Zdcy");
          Gx.setid (Integer.parseint (string.valueof (ID)));
          Gx.setname (Name.tostring ());
          GX.SETJB (Jb.tostring ());
          Gx.setdy (Dy.tostring ());
          Gx.setyear (Year.tostring ());
          GX.SETFZR (Fzr.tostring ());
          GX.SETTBR (Tbr.tostring ());
          Gx.setphone (Phone.tostring ());
          Gx.setemail (Email.tostring ());
          Gx.setwww (WWW.toString ());
          Gx.setgxqmjsum (Gxqmjsum.tostring ());
          GX.SETJCMJ (Jcmj.tostring ());
          Gx.setgxqyy (Gxqyy.tostring ());
          Gx.setgysum (Gysum.tostring ());
          Gx.setgyadd (Gyadd.tostring ());
          Gx.setcztr (Cztr.tostring ());
          GX.SETCZZC (Czzc.tostring ());
          Gx.setdec (Dec.tostring ());

          Gx.setzdcy (Zdcy.tostring ());
        Gxlist.add (GX);
      } parsejsonresult (gxlist, response);
      catch (Exception e) {e.printstacktrace ();

 }

2, Delay loading
because the old project uses the Struts1, causes the foreground form to receive the parameter to have the question, therefore receives directly with the servlet
Front-end JSP like 1 direct load, JS as follows

function Initdatatables () {/*var columns = new Array ();
    $ ("#listTable thead th"). each (function (index, Element) {var fieldname=$ (element). attr ("FieldName"); if (Fieldname.indexof ('. ')
    >0) fieldname=fieldname.substring (2);
  Columns.push ({"Data": FieldName}); 
  });
  if ($ (' #listTable '). length<=0) return;
  --Column definition var columndefs = new Array (); $ ("#listTable thead th"). each (function (index, Element) {if (element). attr ("FieldType")!= ' VARCHAR ') {Co
    Lumndefs.push ({"orderable": True, "searchable": false, "targets": index}); }); */$ (' #listTable '). 
    DataTable ({"Processing": true,//processing Displays "ServerSide": true,//server Handles "sscrolly": "Sscrollx": "100%", "Columns": [{"Data": "ID"},{"Data": "Year"},{"Data": "REGION"},{"Data": "Gyzcz"},{"Data": "Qys"}], * "Columns": columns,*//* "columndefs": columndefs,*///"Binfo": false,//"bpaginate": false,//"Bfilter": False,/servlet/co MpLexinquireservlet//"Blengthchange": false, "Ajax": {"url": urlcontextpath+ "/mst/datatableslazyloadservlet?"                
        Flag=details ", type": "POST", "Data": function (d) {var queryform = Document.queryconditionform;
        d[' fieldcode '] = ' id,year,region,gyzcz,qys '; d[' tablecode '] = ' ODS10000030 ';
      Table name}, "Olanguage": {"search": "Searching in tables:", "Show": "Display", "sprocessing": "Process ...", "Slengthmenu": "Show _menu_ results", "szerorecords": "No Match Results", "Sinfo": "Show _start_ to _end_ item results, total _total_ items
      "," Sinfoempty ":" Show No. 0 to No. 0 results, total 0 items "," sinfofiltered ":" (Filtered by _max_) "," Sinfopostfix ":" ", "Ssearch": "Search:", "sURL": "", "semptytable": "The data in the table is empty", "sloadingrecords": "Load in ...", "Sinfotho
        Usands ":", "," opaginate ": {" Sfirst ":" Home "," sprevious ":" Prev "," Snext ":" Next Page ", "Slast": "Last"}, "Oaria": {"ssortascending": ": Arrange this column in ascending order", "ssortdescending:": In descending order this column "}}}";
ShowPage ();
  function showquerytable () {//Build table $ (' #secondtid '). Remove (); $ ("#tid"). Append ("<div id=" Secondtid ' style= ' width:100%; ') > "+" <table id= ' listtable ' class= ' table table-striped table-bordered table-hover no-footer dataTable disp Lay ' ><thead><tr> "+" <th nowrap>id</th> "+" <th nowrap> year </th> "+" <th nowrap> area </th> "+" <th nowrap> industrial output value (million) </th> "+" <th now Rap> Enterprise Number (Home) </th> "+" </tr></thead><tbody></tbody></table> "+" &L
  T;/div> ");  Create Header/*$.ajax ({url:urlcontextpath+ '/mst/datatableslazyloadservlet?flag=titles ',//Jump to action data : {index: '}, type: ' Post ', success:function (data) {var daTaobj = eval (data); }, Error:function () {alert ("Exception!)"
        ");
////Fill data initdatatables ();

 }

Note: This is already a simplified version of the table header can be passed over with another Ajax, here omitted directly written dead.
Here is the background section

public class Datatableslazyload extends httpservlet{@Override protected void DoPost (HttpServletRequest request, Http
  Servletresponse response) throws Servletexception, IOException {this.process (request, response);
   /** * DataTables delay Load data loading, flag callout details to inject data, titles to inject title. * @param Request * @param response * * private void process (HttpServletRequest request, HttpServletResponse respons
    e) {ServletContext servletcontext=request.getsession (). Getservletcontext ();
    Webapplicationcontext WAC =webapplicationcontextutils.getrequiredwebapplicationcontext (servletContext);

    Dictionaryserviceimpl ds= (Dictionaryserviceimpl) Wac.getbean ("Oracledictionaryservice");
    String flag = Request.getparameter ("flag");
    String Tablecode = Request.getparameter ("Tablecode");

    String Fieldcode = Request.getparameter ("Fieldcode");
    if (flag==null) return; if (Flag.equals ("titles")) {}else if (flag.equals ("Details")) {String draw = Request.getparameter ("Draw");
      String start = Request.getparameter ("Start");
      String length = request.getparameter ("Length");
      StringBuilder sql = new StringBuilder ("select");
      List titles = This.gettitles (Tablecode,fieldcode,ds);      
        for (int i=0;i<titles.size (); i++) {Map record = (MAP) titles.get (i);
      Sql.append (""). Append (Record.get ("FIELDNAME")). Append (",");
      } if (Sql.lastindexof (",") >0) Sql.deletecharat (Sql.lastindexof (","));
      Sql.append ("from"). Append (Tablecode);
      Sql.append ("where 1=1");
      String filtersql = Getfiltersql (titles,request);
      Integer totalcount =ds.getsqlrecordcount ("SELECT count (*) from (" + sql.tostring () + ") tmp");

      Integer Filtercount = Ds.getsqlrecordcount ("SELECT count (*) from (" + sql.tostring () +filtersql+ ") tmp");

      String[] strings = Fieldcode.split (",");
      String ordersql = Getordersql (strings,request);
      Sql.append (Filtersql);
      Sql.append (Ordersql); List<mAp> lt = Ds.executesqltorecordmap (sql.tostring (), integer.valueof (start), integer.valueof (length));
      Map result = new Linkedhashmap ();
      Result.put ("Draw", draw); Result.put ("Recordstotal", TotalCount)//Record Total row number result.put ("recordsfiltered", filtercount);//filtered rows int Coun
      T=integer.valueof (length) +1;
        for (map r:lt) {r.put ("Dt_rowid", R.get ("id"))//Set row primary key Map rowdate = new Linkedhashmap ();//row data
        Rowdate.putall (R);


        R.put ("Dt_rowdata", rowdate);
        R.put ("Countinx", count);
      count++;
      } result.put ("Data", lt);
      try {Convertlisttojson (result, response);
      catch (Exception E1) {//TODO auto-generated catch block E1.printstacktrace (); /** * Gets all column header names * @return/private List gettitles (String tablecode,string Fieldcode,dictiona Ryserviceimpl ds) {/*stringbuilder sql = new StringBuilder ("Select UPPER (ods_df_name) fieldname,oDs_df_cn_name fieldlabel,ods_df_code fieldcode,upper (ods_df_data_type) FieldType from ODS.
    Ods_df_info_reg ");
    Sql.append ("Where ods_tb_code= '" +tablecode+ "");
    list<map> list = Ds.executesqltorecordmap (sql.tostring ()); return list;*/StringBuilder sql = new StringBuilder ("Select UPPER (ods_df_name) fieldname,ods_df_cn_name Fieldlabel," Ods_df_code Fieldcode,upper (Ods_df_data_type) FieldType from ODS.
    Ods_df_info_reg ");
    Sql.append ("where 1=1");
    Sql.append ("and Ods_tb_code = '" +tablecode+ ");
    Sql.append ("and Ods_df_name in");
    string[] tmp = Fieldcode.split (",");
    StringBuilder ids = new StringBuilder ();
      for (String t:tmp) {if (Stringutils.isempty (t)) continue;
    Ids.append ("'"). Append (t). Append ("',");
    } if (Ids.lastindexof (",") >0) Ids.deletecharat (Ids.lastindexof (","));
    Sql.append (IDS);    
    Sql.append (")");
    List lt = Ds.executesqltorecordmap (sql.tostring ());
  Return lt; /** * Front Search * @paraM FIELDLT * @return/private String Getfiltersql (list<map> fieldlt,httpservletrequest request) {Strin
    Gbuilder filtersql = new StringBuilder ("and");
    String Searchkey = "Search[value]";
    String Searchvalue = Request.getparameter (Searchkey);
    System.out.println (Searchvalue);
    if (Stringutils.isempty (searchvalue)) return "";
    list<string> filterdetail = new ArrayList ();
      for (int i=0;i<fieldlt.size (); i++) {Map field = Fieldlt.get (i);    
        if (Field.get ("FieldType"). Equals ("VARCHAR")) {String subkey = "columns[" +i+ "][searchable");


          if ("true". Equals (Request.getparameter (subkey))) {String fieldName = field.get ("FieldName"). ToString ();
          String Subsql = fieldName + "Like '%" +searchvalue+ "%";
        Filterdetail.add (Subsql);
    }} if (Filterdetail.size () ==0) return "";
    Boolean F = true;
        for (String subsql:filterdetail) {if (f) {f= false; FilterSQl.append (Subsql);
      }else{filtersql.append ("OR"). Append (Subsql);

    } filtersql.append (")");
  return filtersql.tostring (); /** * Sort * @param FIELDLT * @return/private String Getordersql (string[) titles,httpservletrequest re
    Quest) {StringBuilder ordersql = new StringBuilder ("Order by");
    String Indexkey = "Order[0][column]";
    String Dirkey = "Order[0][dir]";
    Integer columnindex = integer.valueof (Request.getparameter (Indexkey));
    String dir = request.getparameter (Dirkey);
      if (columnindex<=titles.length) {ordersql.append (Titles[columnindex]). Append (""). Append (dir);
    return ordersql.tostring ();
  Return ""; } public void Convertlisttojson (Map map,httpservletresponse response) throws exception{Jsonarray json = JSONARRAY.F 
    Romobject (map);
    Response.setheader ("Cache-control", "No-cache"); Response.setcontenttype ("text/html; 
    CHARSET=GBK ");
    PrintWriter writer; Writer= Response.getwriter ();
    Writer.write (Json.get (0). toString ());
  Writer.close ();

 }
}

Summary, do more urgent, also did not properly tidy up directly posted out, because it is not difficult, there must be a place to write a bad, for reference only.

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.