刷新表后对DataTable进行排序和搜索

背景:我有一个包含小部件的小型jquery应用程序。 这个应用程序有两种类型的小部件,它们是计数器小部件和网格小部件。 对于网格小部件,我正在使用dataTables 。

我的应用程序基本上连接到服务器,并收集各种信息,如小部件名称和计数器和网格小部件的值。 因此,根据收到的信息,我为每个小部件动态创建页面。 目前情况正常,但我面临一个小问题。

问题我现在遇到的问题是我的网格小部件使用dataTables api。从我的服务器我收到这种格式的网格信息。

**//EXAMPLE INPUT /*    Player State Points   Lebron King James Best Mode 45   */** 

然后我解析它并将其插入表中。 问题是我每3秒做一次更新,因为网格数据实时更新。 因此,当我进行更新时,我的搜索filter和排序会重置。

所以例如下面,如果我按最高分排序

 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 

我的HTML代码

     NBA Fanatico                      

Basketball Fanatico

  • WELCOME!
  • Use the menu on the left to navigate
    and configure the various options.
<!--
--> <!--
-->

我的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 = 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(/w\d+\.isHidden(.*)\(\) == false\)[\s\S]*?catch\(err\)\{ \}/gm); for (var i = 0; i  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  -1) { //Header FOR grid Widget Page var pageHeaderPart = "

Basketball Fanatico

"; } else { //Header For Counter Widget Page var pageHeaderPart = "

Basketball Fanatico

"; } //Footer for all Widget Pages var pageFooterPart = "
"; if (testwidget[i].indexOf('hi') > -1) { //Grid Page widget title var check = "
  • " + widgetNames[i] + ""; } //Counter Page widget title var check = "
    • " + widgetNames[i] + "
    "; if (testwidget[i].indexOf('counterValue') > 0) { //Counter Content (actual value of the counter widget) widgetPart[i] = '
    ' + 'function UpdateWidgetDiv' + widgetId[i] + '() {' + testwidget[i] + '$(\"#widgetContainer_' + widgetId[i] + '").html(counterValue);' + '}' + ''; } if (testwidget[i].indexOf('hi') > -1) { //Grid content(actual values for the grid widget) widgetPart[i] = '
    ' + 'function UpdateWidgetDiv' + widgetId[i] + '() {' + testwidget[i] + '}' + ''; } else { //Miscalenous content(these are counter widgets that will contain text messages for now just putting "i dont know what i am") widgetPart[i] = '
    I dont know what I am
    '; } AllWidgets += '' + widgetNames[i] + ''; var makePage = $(pageHeaderPart + check + widgetPart[i] + pageFooterPart); makePage.appendTo($.mobile.pageContainer); } $('#items').prepend(AllWidgets).trigger('create'); //Widget Update Function function UpdateActivePage() { //get active page pageId = $(":mobile-pagecontainer").pagecontainer('getActivePage').prop("id"); //figure out index var idx; for (var i = 0; i < widgetId.length; i++) { if (widgetId[i] == pageId) { idx = i; break; } } eval(testwidget[idx]); $("#widgetContainer_" + pageId).html(counterValue); $('#grid_' + idx).dataTable({ "bPaginate": false, "bFilter": true, "bAutoWidth": false, "oLanguage": { "sSearch": "" } }); $('.dataTables_filter input').attr("placeholder", "Search"); $('.dataTables_filter').css('float', 'none'); $('.dataTables_filter').css('padding-right', '0px'); $("#example_filter").detach().prependTo('#header1'); } function CreateGridUpdateFunction(oldUpdatefunction, thisWidgetID) { var updateLines = oldUpdatefunction.split("\n"); var updateFunctionCode = ""; for (var i = 0; i 0) { //alert(updateLines[i]); // updateFunctionCode = " try { "; var updateURL = updateLines[i]; if (updateURL.indexOf("&windowWidth=") > 0) { updateURL = updateURL.substr(0, updateURL.lastIndexOf("&windowWidth=")) + "';"; //console.log(updateURL); } updateFunctionCode += updateURL; updateFunctionCode += " var loader = dhtmlxAjax.getSync(url);"; updateFunctionCode += " if(loader.xmlDoc.responseText.length > 0){"; updateFunctionCode += " counterValue = createTableStringFromXML(loader.xmlDoc.responseText," + thisWidgetID + ");"; updateFunctionCode += " } "; } } return "var counterValue = \"hi\"; " + updateFunctionCode; } $(":mobile-pagecontainer").on("pagechange", function () { UpdateActivePage(); }) setInterval(UpdateActivePage, 3000); } }); }); }); //Returns a bool indicated if the (space trimmed) string starts with needle. function startsWith(searchString, searchVal) { var search = searchString.trim(); return search.indexOf(searchVal) >= 0; } function createTableStringFromXML(serverXML, thisWidgetID) { //EXAMPLE INPUT /* Player State Points Lebron James Injured 25 */ console.log(serverXML); //PARSE THE ABOVE XML STRING to required FORMAT var xmlLines = serverXML.split("\n"); var returnTable = ""; for (var i = 0; i < xmlLines.length; i++) { if (startsWith(xmlLines[i], "<rows")) { returnTable += ""; } else if (startsWith(xmlLines[i], "")) { returnTable += "
    "; } else if (startsWith(xmlLines[i], "")) { returnTable += ""; } else if (startsWith(xmlLines[i], "")) { returnTable += ""; } else if (startsWith(xmlLines[i], "<column")) { returnTable += "" + xmlLines[i].match(/>(.*?)</i)[1] + ""; } else if (startsWith(xmlLines[i], "<row")) { returnTable += ""; } else if (startsWith(xmlLines[i], "</row")) { returnTable += ""; } else if (startsWith(xmlLines[i], "<cell")) { returnTable += "" + xmlLines[i].match(/>(.*?)</i)[1] + ""; } console.log(returnTable); } return returnTable; }

请告诉我如何解决这个问题我已经被困在这一个星期了几乎我很抱歉,如果这个问题很糟糕,因为我只有几个月新的js和html和web开发一般。 我也为我可怜的英语道歉。

EZ更新的代码

查看以//EZ开头的评论:

  function UpdateActivePage() { //get active page pageId = $(":mobile-pagecontainer").pagecontainer('getActivePage').prop("id"); //figure out index var idx; for (var i = 0; i < widgetId.length; i++) { if (widgetId[i] == pageId) { idx = i; break; } } eval(testwidget[idx]); if (counterValue == false) { //EZ: no need to recreate datatable return; } else { $("#widgetContainer_" + pageId).html(counterValue); $('#grid_' + idx).dataTable({ "bPaginate": false, "bFilter": true, "bAutoWidth": false, "oLanguage": { "sSearch": "" } }); $('.dataTables_filter input').attr("placeholder", "Search"); $('.dataTables_filter').css('float', 'none'); $('.dataTables_filter').css('padding-right', '0px'); $("#example_filter").detach().prependTo('#header1'); } } function createTableStringFromXML(serverXML, thisWidgetID) { //EXAMPLE INPUT /*    Player State Points   Lebron James Injured 25    */ console.log(serverXML); //PARSE THE ABOVE XML STRING to required FORMAT var xmlLines = serverXML.split("\n"); var returnTable = ""; //EZ: See if table already exists if ( $("#grid_" + thisWidgetID).length > 0){ //EZ: update table using the datatables API... //EZ: then return false return false; } else { for (var i = 0; i < xmlLines.length; i++) { if (startsWith(xmlLines[i], "<rows")) { returnTable += ""; } else if (startsWith(xmlLines[i], "")) { returnTable += "
"; } else if (startsWith(xmlLines[i], "")) { returnTable += ""; } else if (startsWith(xmlLines[i], "")) { returnTable += ""; } else if (startsWith(xmlLines[i], "<column")) { returnTable += "" + xmlLines[i].match(/>(.*?)</i)[1] + ""; } else if (startsWith(xmlLines[i], "<row")) { returnTable += ""; } else if (startsWith(xmlLines[i], "</row")) { returnTable += ""; } else if (startsWith(xmlLines[i], "<cell")) { returnTable += "" + xmlLines[i].match(/>(.*?)</i)[1] + ""; } console.log(returnTable); } } return returnTable; }

Datatables有一个丰富的api( http://datatables.net/api ),可以在保持排序的同时添加,删除和更新行。 在您的情况下,新数据可能需要删除不再存在于XML中的行,更新现有行以及添加XML中但不在表中的新行。

可能最简单的方法是调用fnClearTable删除所有当前行并使用fnAddData添加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