Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
667 views
in Technique[技术] by (71.8m points)

javascript - Sorting and Searching DataTables after refreshing table

BACKGROUND: I have a small jquery app that contains widgets. There are 2 types of widgets in this app and they are counter widgets and grid widgets. For grid widgets i am utilizing dataTables.

My app basically connects to a server and recieves various information such as widget names and values for the counter and grid widgets. So based on the information received i dynamically create pages for each widget. Things are working fine at the moment but i am facing a little problem.

Problem The issue i have right now is to do with my grid widgets which utilize dataTables api.From my server I receive the grid information in this format.

**//EXAMPLE INPUT
/*
<?xml version="1.0" encoding="UTF-8"?>
<rows>
    <head>
        <column width="55" type="ro" align="left" sort="str">Player</column>
        <column width="55" type="ro" align="left" sort="str">State</column>
        <column width="55" type="ro" align="left" sort="str">Points</column>
    </head>
     <row id="1">
        <cell>Lebron King James</cell>
        <cell>Best Mode</cell>
        <cell>45</cell>
     </row>
</rows>
*/**

I then parse this and insert it in the tables. The problem is i am doing a update every 3 seconds since the data for grid gets updated in real time . So when i do a update my search filter and sorting is reset.

So for example below if i am sorting by highest points

PLAYER         POINTS
KING JAMES     45
DERRICK ROSE   30 

UPDATE HAPPENS AND MY SORTING WILL GET REST TO THIS

PLAYER         POINTS
DERRICK ROSE    30
KING JAMES      45 

MY HTML CODE

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta name="generator" content="HTML Tidy for Windows (vers 14 February 2006), see www.w3.org" />
    <title>
      NBA Fanatico
    </title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <link rel="stylesheet" href="themes/tdMobile.min.css" type="text/css" />
    <link rel="stylesheet" href="themes/jquery.mobile.icons.min.css" type="text/css" />
    <link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.0/jquery.mobile.structure-1.4.0.min.css" type="text/css" />
    <link rel="stylesheet" type="text/css" href="cssfinal/style.css" />
    <script src="http://code.jquery.com/jquery-1.10.2.min.js" type="text/javascript"></script>
    <script src="http://code.jquery.com/mobile/1.4.0/jquery.mobile-1.4.0.min.js" type="text/javascript"></script>
    <script src="dhtmxSuite/dhtmlxWindows/codebase/dhtmlxcommon.js" type="text/javascript"></script>
    <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.min.js" type="text/javascript"></script>
    <script src="jquery.ui.touch-punch.min.js" type="text/javascript"></script>
    <!-- MAIN JS SCRIPT CONTANS CODE FOR COUTNER WIDGETS, TABLES , AJAX REQUEST FOR GETTING DATA-->
    <script src="dynamic.js" type="text/javascript"></script>
    <!-- SCRIPTS FOR DATA TABLES -->
    <!-- DataTables CSS -->
    <link rel="stylesheet" type="text/css" href="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/css/jquery.dataTables.css" /><!-- DataTables -->
    <script type="text/javascript" charset="utf8" src="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/jquery.dataTables.min.js"></script>
  </head>
  <body>
    <!-- PAGE 1 -->
    <div data-role="page" data-theme="a" id="page1">
      <div data-role="content" data-theme="a">
        <div class="login-box" id="login">
          <div id="loginprompt">
            <div id="header">
              <h3>
                Basketball Fanatico
              </h3>
            </div>
          </div>
          <form method="get">
            <div id="username" data-role="fieldcontain">
              <input type="text" name="username" placeholder="Username" />
            </div>
            <div id="password" data-role="fieldcontain">
              <input type="password" name="password" id="txtId" placeholder="Password" />
            </div>
            <div id="loginbtn">
              <a data-role="button" id="log" data-theme="a" href="#page2" data-transition="slide">LOGIN</a>
            </div>
          </form><br />
        </div>
      </div>
    </div><!-- PAGE 2 -->
    <div data-role="page" id="page2">
      <div data-role="header" data-position="fixed" data-theme="a">
        <a data-iconpos="notext" href="#panel" data-role="button" data-icon="bars"></a>
        <h1 class="ui-title" role="heading">
          Basketball Fanatico
        </h1>
        <div class="ui-btn-right" data-type="horizontal">
          <a data-iconpos="notext" href="#page2" data-role="button" data-icon="home"></a> <a data-iconpos="notext" href="#page1" data-role="button" data-icon="delete"></a>
        </div>
      </div>
      <div data-role="content" id="page2content">
        <ul data-role="listview" data-inset="true">
          <li data-role="list-divider" data-theme="a">WELCOME!
          </li>
          <li>Use the menu on the left to navigate<br />
            and configure the various options.
          </li>
        </ul>
      </div>
    </div>
    <div data-role="panel" id="panel" data-position="left" data-theme="a" data-display="push">
      <!--  <div> -->
      <div id="nav">
        <h3>
          Navigation
        </h3>
        <hr />
        <label><input id="chkSort" type="checkbox" checked="true" />Allow sorting</label>
        <hr />
      </div>
      <div id="items" data-role="button">
        <!-- Insert Parsed Widget Names Here -->
        <a href="#page1" data-transition="fade" data-theme="a" data-role="button">LOG OUT</a>
      </div><!-- </div> -->
    </div>
  </body>
</html>

MY JS

var widgetNames = new Array();
var widgetId = new Array();
var pageId = ''

$(document).on("pagecreate", function () {
    $("body > [data-role='panel']").panel().enhanceWithin();
});

$(document).on('pagecreate', '#page1', function () {
    $("#log").on('click', function () {
        $.ajax({
            url: "script.login",
            type: "GET",
            data: {
                'page': 'create_user',
                'access': 'user',
                'username': $("input[name='username']").val(),
                'password': $("input[name='password']").val()
            },
            dataType: "text",
            success: function (html) {
                widgetNames = new Array();
                widgetId = new Array();
                var res = html.match(/insertNewChild(.*);/g);
                //Get each widget name and ID and assign to values in an array
                for (var i = 0; i < res.length; i++) {
                    //alert(res[i]);
                    var temp = res[i].split(',');
                    if (temp.length >= 3) {
                        widgetNames[i] = (temp[2].replace('");', '')).replace('"', '');
                        widgetId[i] = temp[1].replace("'", "").replace("'", "").replace(/ /g, '');
                    }
                }
                var AllWidgets = ''
                var testwidget = new Array();
                //Loop through the html returned and get the data relevant to each widget... save in temp array                            
                var tempWidgetContent = html.match(/wd+.isHidden(.*)() == false)[sS]*?catch(err){ }/gm);
                for (var i = 0; i < tempWidgetContent.length; i++) {
                    var widgetContent = tempWidgetContent[i].substring(tempWidgetContent[i].indexOf('{') + 1);
                    testwidget[i] = widgetContent.replace("site +", "");
                    //replace the code for a grids...
                    if (testwidget[i].indexOf('grid') > 0) {
                        testwidget[i] = CreateGridUpdateFunction(testwidget[i], i);
                    }
                }

                var widgetPart = new Array();
                //Assume we have widget names, ids, and loading data in 3 arrays
                //Loop through and create the necessary page.
                for (var i = 0; i < widgetNames.length; i++) {
                    if (testwidget[i].indexOf('hi') > -1) {
                        //Header FOR grid Widget Page
                        var pageHeaderPart = "<div data-role= 'page' id='" + widgetId[i] + "' data-pageindex='" + i + "' class='dynPageClass'><div data-role='header' id='header1' data-position='fixed' data-theme='a'><a href='#panel' data-icon='bars' data-iconpos='notext' class='ui-btn-left'></a><a href='#' data-icon='search' id='search' data-iconpos='notext' class='ui-btn-left' style='margin-left: 35px'></a><h1>Basketball Fanatico</h1><a href='#page1' data-icon='delete' data-iconpos='notext' class='ui-btn-right'></a><a href='#page2' data-icon='home' data-iconpos='notext' class='ui-btn-right' style='margin-right: 35px;'></a></div><div data-role='content'>";
                    } else {
                        //Header For Counter Widget Page
                        var pageHeaderPart = "<div data-role='page' id='" + widgetId[i] + "' data-pageindex='" + i + "' class='dynPageClass'><div data-role='header'data-position='fixed' data-theme='a'><a data-iconpos='notext' href='#panel' data-role='button'data-icon='bars'></a><h1 class='ui-title'role='heading'>Basketball Fanatico</h1><div class='ui-btn-right' data-type='horizontal'><a data-iconpos='notext' href='#page2' data-role='button'data-icon='home'style=" margin-right:5px; "></a><a data-iconpos='notext' href='#page1' data-role='button'data-icon='delete'></a></div></div><div data-role='content'>";
                    }

                    //Footer for all Widget Pages
                    var pageFooterPart = "</div><div data-role='footer' data-position='fixed'><span class='ui-title'><div id='navigator'></div></span></div></div>";

                    if (testwidget[i].indexOf('hi') > -1) {
                        //Grid Page widget title
                        var check = "<div data-role='tbcontent'><ul data-role='listview'data-insert='true'><li data-role='list-divider' data-theme='a'>" + widgetNames[i] + "";
                    }

                    //Counter Page widget title
                    var check = "<div data-role='content'><ul data-role='listview'data-insert='true'><li data-role='list-divider' data-theme='a'>" + widgetNames[i] + "</div>";

                    if (testwidget[i].indexOf('counterValue') > 0) {
                        //Counter Content (actual value of the counter widget)
                        widgetPart[i] = '<DIV style=" text-align: center; background-color:#EDEDED;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Datatables has a rich api (http://datatables.net/api) that provides for adding, deleting, and updating rows while keeping the sorting. In your case, the new data might require deleting rows that are no longer in the XML, updating existing rows, and adding new rows that are in the XML but not in the table.

Probably the easiest thing would be to call fnClearTable to remove all current rows and use fnAddData to add all the rows in the XML:

var oTable = $('#example').dataTable();
oTable.fnClearTable();

$xml.find("row").each(function(index){            
    var $cells = $(this).find("cell");
    var c1 = $cells.eq(0).text();
    var c2 = $cells.eq(1).text();
    var c3 = $cells.eq(2).text();

    oTable.fnAddData( [c1, c2, c3]);
});  

DEMO


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...