如何排序和搜索使用ajax

时间:2018-06-04 06:12:07

标签: sorting dom nodelist

我试过这个来搜索dom元素并显示匹配的行,但它在某些列中不起作用,例如duration和bytes.It适用于重复的元素,例如,如果有507值,则两倍于字节,它可以工作但不适用于411 。我正在读取文件内容并将其制表,然后需要在单击标题时对行进行排序并应用过滤器。

<!DOCTYPE html>
<html>
 <meta charset="UTF-8"> 
    <head>
        <style type="text/css">
             body
             {
                 font-family: Arial;
                    font-size: 10pt;
             }
            table
            {
                 border: 1px solid #ccc;
                  margin: auto;
              empty-cells: hide;
            }
             table th
             {
                 background-color: GREY;
                    color: #333;
                    font-weight: bold;
            cursor:pointer;
                }
            table th, table td
             {
                 padding: 5px;
                 border: 1px solid #ccc;
                 border-color: #ccc;

               }

             #sear
        {
         background-color: black;

        height:30px;
        width:105%;
        align : center;
        }
        tr:nth-child(even) {
         background-color: #f2f2f2
        }

            tr:hover {
         background-color: silver;
        }
          </style>

     <meta name="viewport" content="width=device-width,height=device-height, initial-scale=1">
     <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
     <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
   </head>
   <body>

        <div id="sear" align = center>
        <input type="text" id="filter" placeholder="Search" title="Type a name" >
        </div>
        <div id="demo" align = center >

        </div>

        <script>
            window.onload = function() {
             var demo = document.getElementById("demo");
              if(window.XMLHttpRequest){
                 var xhttp = new XMLHttpRequest();
              }
              else{
                   var xhttp = new ActiveXObject("Microsoft.XMLHTTP");
               }
               xhttp.onreadystatechange = function() {
              if (this.readyState == 4 && this.status == 200 || this.status == 0) {
              var responseText= xhttp.responseText;
  //alert(responseText);
            //  console.log(this.responseText);
              document.getElementById("filter").onkeyup = filterRows;
              var ROW_DELIMITER = "\n",  CELL_DELIMITER = " ";

              var tableObj = { headers: ["Time", "Duration", "Client address", "Result codes", "Bytes", "request method", "URL", "user", 

"Hierarchy code", "Type"], 
                rows: []
               };
            }

             function convert(responseText) {
               tableObj.rows = convertToArray(responseText);
               buildTable(tableObj.headers, tableObj.rows);
              };

            function convertToArray(text) {
                 return text.split(ROW_DELIMITER).map(function(row) {
                     return row.split(CELL_DELIMITER);
                    });
            }


              function filterRows() {
                    var input = this;
                    var rows = tableObj.rows.filter(function(row) {

                      var matches = row.filter(function(cell) { 
                            return cell.toUpperCase().indexOf(input.value.toUpperCase()) > -1;
                        });

                     return matches.length > 0;
                              });

                      buildTable(tableObj.headers, rows);
            }



              function sortRows() {

                   var index = this.dataset.index;
                   tableObj.rows.sort(function(rowA, rowB) {
                      var textA = rowA[index].toUpperCase(), textB = rowB[index].toUpperCase();
                     if (textA < textB) {
                       return -1;
                      }
                    if (textA > textB) {
                       return 1;
                    }
                       return 0;
                    });

                 buildTable(tableObj.headers, tableObj.rows);
            }


            function buildTable(headers, rows) {
                  var table = document.createElement('table');
                      var tr = document.createElement('tr');
                   table.appendChild(tr);

                 for (var i = 0; i < headers.length; i++) {
                         th = document.createElement('th');
                         tr.appendChild(th);
                         th.innerHTML = headers[i];
                         th.onclick = sortRows; 
                          th.dataset.index = i;
                    }

                 for (var j = 0; j < rows.length-1; j++) {
                          tr = document.createElement('tr');
                       table.appendChild(tr);
                       tr.dataset.index = j;
                         for (var k = 0; k < rows[j].length ; k++) {
                              var td = document.createElement('td');

    /*                    if(k==0)
                          {
                            var d = new Date( rows[j][k]* 1000),    
                            yyyy = d.getFullYear(),
                            mm = ('0' + (d.getMonth() + 1)).slice(-2),  
                            dd = ('0' + d.getDate()).slice(-2),         
                            hh = d.getHours(),
                            h = hh,
                            min = ('0' + d.getMinutes()).slice(-2),     
                            ampm = 'AM',
                            time;

                            if (hh > 12) {
                                h = hh - 12;
                                ampm = 'PM';
                            } else if (hh === 12) { 
                                h = 12;
                                ampm = 'PM';
                            } else if (hh == 0) {
                                h = 12;
                            }


                            rows[j][k] = dd + '.' + mm + '.' + yyyy + ', ' + h + ':' + min + ' ' + ampm;


                        }
    */

                        tr.appendChild(td);
                             td.innerHTML = rows[j][k];
                            td.dataset.index = k;
                    }
                }
                demo.innerHTML = '';
                demo.appendChild(table);
          }

         convert(responseText);
        };
     xhttp.open("GET", "sample.txt", true);
     xhttp.send(null);
    };
    </script>
</body>
</html>

1 个答案:

答案 0 :(得分:1)

以下是更新后的代码:

window.onload = function() {
            var demo = document.getElementById("demo");
            if (window.XMLHttpRequest) {
                var xhttp = new XMLHttpRequest();
            } else {
                var xhttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
            xhttp.onreadystatechange = function() {
                if (this.readyState == 4 && this.status == 200 || this.status == 0) {
                    var responseText = xhttp.responseText;
                    console.log(this.responseText);
                    document.getElementById("filter").onkeyup = filterRows;
                    var ROW_DELIMITER = "\n",
                        CELL_DELIMITER = " ";
                    var tableObj = {
                        headers: ["Time", "Duration", "Client address", "Result codes", "Bytes", "request method", "URL", "user", "Hierarchy code", "Type"],
                        rows: []
                    };
                }

                function convert(responseText) {
                    if(responseText!='' && typeof responseText != 'undefined'){
                        tableObj.rows = convertToArray(responseText);
                        buildTable(tableObj.headers, tableObj.rows);
                    }
                };

                function convertToArray(text) {
                    return text.split(ROW_DELIMITER).map(function(row) {
                        return row.split(CELL_DELIMITER);
                    });
                }


                function filterRows() {
                    var input = this;
                    var rows = tableObj.rows.filter(function(row) {
                        var matches = row.filter(function(cell) {
                            //console.log(cell.toUpperCase())
                         //   console.log(input.value.toUpperCase())
                         //   console.log(cell.toUpperCase().indexOf(input.value.toUpperCase()))
                            return cell.toUpperCase().indexOf(input.value.toUpperCase()) > -1;
                        });
                        return matches.length > 0;
                    });
                    buildTable(tableObj.headers, rows);
                }



                function sortRows() {

                    var index = this.dataset.index;
                    tableObj.rows.sort(function(rowA, rowB) {
                        var textA = rowA[index].toUpperCase(),
                            textB = rowB[index].toUpperCase();
                        if (textA < textB) {
                            return -1;
                        }
                        if (textA > textB) {
                            return 1;
                        }
                        return 0;
                    });

                    buildTable(tableObj.headers, tableObj.rows);
                }


                function buildTable(headers, rows) {
                    var table = document.createElement('table');
                    var tr = document.createElement('tr');
                    table.appendChild(tr);

                    for (var i = 0; i < headers.length; i++) {
                        th = document.createElement('th');
                        tr.appendChild(th);
                        th.innerHTML = headers[i];
                        th.onclick = sortRows;
                        th.dataset.index = i;
                    }

                    for (var j = 0; j <= rows.length - 1; j++) {
                        tr = document.createElement('tr');
                        table.appendChild(tr);
                        tr.dataset.index = j;
                        for (var k = 0; k < rows[j].length; k++) {
                            var td = document.createElement('td');


                            tr.appendChild(td);
                            td.innerHTML = rows[j][k];
                            td.dataset.index = k;
                        }
                    }
                    demo.innerHTML = '';
                    demo.appendChild(table);
                }
                convert(responseText);
            };
            xhttp.open("GET", "sample.txt", true);
            xhttp.send(null);
        };