开发者

Communicate between PHP and Javascript

开发者 https://www.devze.com 2023-02-03 21:49 出处:网络
I have a table in database that has 2 columns Name | Age, I display it in a HTML page. I want to sort the table in HTML page based on a field 开发者_Python百科when the user clicks on it.

I have a table in database that has 2 columns Name | Age, I display it in a HTML page.

I want to sort the table in HTML page based on a field 开发者_Python百科when the user clicks on it.

I have a PHP function to do the sorting based on a field.

But after obtaining the rows in sorted order in PHP, I'm looking for ways by which I can update the HTML table without navigating away from the page.


You do not need to communicate between the client and server to do this, just sort the table on the client directly.

There is a jQuery plug-in for this that works quite well:

http://tablesorter.com/docs/


You can do sorting in javascript, without having to communicate with the server. For example, this code will sort a table based on the content of the Nth column:

function sortTable(table, column, skipHeader) {
  // Stick each row into an array.
  var rows = [];
  for (var i = skipHeader ? 1 : 0; i < table.rows.length; i++) {
    rows.push(table.rows[i]);
  }

  // Sort the array based on the innerText of the column'th cell in each row
  rows.sort(function(a, b){ 
    a = a.cells[column].innerText;
    b = b.cells[column].innerText;
    return a < b ? -1 : (b < a ? 1 : 0);
  });

  // Re-order the rows by removing/appending in the sort order
  for (var i = 0; i < rows.length; i++) {
    var row = rows[i];
    var container = row.parentElement;
    container.removeChild(row);
    container.appendChild(row);
  }
}

For example, to sort the first table in the document, on the first column, and skip the header row:

sortTable(document.getElementsByTagName('table')[0], 0, true);

Obviously you'll want to modify this to suit your own tastes, especially the sorting, but it's a lot simpler than having to post the data back to the server, which I think is what you're proposing.


Since others have covered the fact that client-side sorting would work just fine here, I'll just point you to the resource with which I've had the most sucess doing this kind of thing: Google Data Tables, part of their Visualization Library. Here are the deets on what you can do (spoiler: everything you want and more).


Here is a link to a javascript library to make your tables sortable using javascript instead of php. I've used it many times, it works great.

Javascript Sortable Tables by: Stuart Langridge

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号