Updating table from JSON/MYSQL with jQuery

巧了我就是萌 提交于 2019-12-14 02:14:11

问题


I'm curious as to what the most acceptable/effective approach is to using tables with data from json.

I have one project in development where I need to update individual cells of a table, based on a mysql table. My X axis labels would be assorted dates (also pulled from mysql). The Y axis labels are times (These are always the same and as such could be generated statically). The content of the table would be available appointment slots (also pulled from mysql).

This table is purely reading off of mysql, as such does need to update the table. I need to refresh the table contents every 15 seconds (without refreshing the page obviously). So my question what is the best way to give reference each cell so I can programatically update them with my json output. This would also need the ability to remove a column if a day has been removed from the appointment roster.

Any assistance would simply be amazing.


回答1:


You could do it like this

Your table generation:

<?php
// example for one col
while($array = mysql_fetchassoc($result))
{
    ?>
    <tr>
      <td id="col_name_<?=$array['row_id']?>"><?=$array['col_val']?></td>
    </tr>
    <?
}
?>

Your AJAX respond should look like this

<?php
while($array = mysql_fetchassoc($result))
{
    ?>
      $('#col_name_<?=$array['row_id']?>').html('<?=$array['col_val']?>');
    <?
}
?>



回答2:


I think the key features are

  • javascript setTimeout() to fetch data every 15sec.
  • a kind of hash comparison between client & server data to see if there is a modification
  • a php function that extract just the modifications to apply
  • a javascript to update the appointments sent by JSON

Maybe you should use a calendar tool for rendering.
Fullcalendar is a pretty good open-source solution for that.

For the updates, I would approach this by presenting the data like:

appointment_id, timestamp_start, timestamp_end, ...

With that you can know if the appointment already exists or if it's a modification (update or delete)
You can also deduce the dates to display


Edit

Since your table is not that big and always day/hour based, this will be much simpler to manage:

Javascript setTimeout() to fetch data every 15sec,
Retrieve the entire table by JSON,
Load it by building up the HTML with jQuery like:

table = $('#table_container');
/* data -> appointments indexed by hours/days fetched by JSON
 * x -> days, y -> hours
 */
for (y=0; data[y].length; y++) {
  tr = $('<tr />');
  table.append(tr);
  for (x=0; data[y][x]; x++) {
    td = $('<td />');
    td.html(data[y][x]);
    tr.append(td);
  }
}

not tested but rough idea



来源:https://stackoverflow.com/questions/8800659/updating-table-from-json-mysql-with-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!