简体   繁体   English

在PHP中生成HTML表并将其传递给Javascript

[英]Generating HTML tables in PHP and passing into Javascript

Essentially, I am trying to build a booking system. 本质上,我正在尝试构建预订系统。 The booking table shows the bookings for an entire week, and the user can switch between weeks. 预订表显示一整周的预订,用户可以在几周之间切换。

In PHP, I have a function get_booking_table which returns the html for the booking table, based on an input (which week) and booking availabilities (from mysql): 在PHP中,我有一个函数get_booking_table,它根据输入(哪个星期)和预订可用性(来自mysql)返回预订表的html:

<?php
  function get_booking_table($week_number) {
    //retrieve various data from mysql database, return html string
  }

I am then loading this html for each week into a JS array, so that the table for each week can be loaded quickly when the user changes week. 然后,我将每周的html加载到JS数组中,以便当用户更改周时可以快速加载每周的表。

My problem is that the HTML string being returned from the PHP function is very long, which I have read is bad practice (as well as being clunky for me to handle). 我的问题是从PHP函数返回的HTML字符串很长,我读过这是不好的做法(而且我很难处理)。 The only way I can think of to avoid this is to instead create a 2D array for the booking table for each week, somehow pass this into JS code, and then generate the HTML code from the JS 2D array. 我想避免这种情况的唯一方法是改为每周为预订表创建一个2D数组,以某种方式将其传递给JS代码,然后从JS 2D数组生成HTML代码。 However, this seems even more overly complicated. 但是,这似乎过于复杂。

What is the correct way to create a dynamic HTML table in PHP and load it into JS? 在PHP中创建动态HTML表并将其加载到JS的正确方法是什么?

Pretty much what the others have stated. 其他人所说的差不多。 This used to be my "go-to" method for a long time: have PHP echo out some nice HTML and "spit it out" on the javascript side. 长期以来,这一直是我的“首选”方法:让PHP回显一些漂亮的HTML,并在javascript端“吐出来”。 Works for some situations, but usually "feels" lazy (to me personally). 适用于某些情况,但通常(对我个人而言)是“懒惰的”。

The best method is as described: Use an ajax request to your PHP page that outputs a json_encoded PHP array (it's literally just wrapping your normal PHP array in the json_encoded function). 最佳方法如下所述:在您的PHP页面上使用ajax请求,该请求输出一个json_encoded PHP数组(实际上只是将普通的PHP数组包装在json_encoded函数中)。 Then, in your ajax's "success" method, go to town parsing the json object. 然后,在您的ajax的“成功”方法中,去解析json对象。 You can use a library like DataTables (that was mentioned) to do this REALLY fast, and it gives you a lot of added functionality (sorting, re-ordering columns, etc.) 您可以使用诸如DataTables(已提到)之类的库来真正快速地完成此操作,并且它为您提供了许多附加功能(排序,重新排序列等)。

Also worth noting, it doesn't sound like you're doing anything with the HTML once it's generated. 同样值得一提的是,它听起来并不像您在生成HTML之后就对其进行任何处理。 So if you wanted to, you could do exactly as you're already doing and output the HTML from your PHP script. 因此,如果您愿意,可以完全按照您已经做的方式进行操作,并从PHP脚本中输出HTML。 Not pretty (or fun to maintain), but it works... 不太漂亮(或维护起来很有趣),但是可以工作...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM