使用 JavaScript 获取表上的 JSON

Fetching the JSON on Table using JavaScript

提问人:Carlmalone Mabiog 提问时间:11/15/2023 最后编辑:Danny Fardy Jhonston BermúdezCarlmalone Mabiog 更新时间:11/16/2023 访问量:93

问:

我正在使用服务器PHP从数据库中检索数据并将其存储为JSON格式。然后 JavaScript 将创建一个表,时间从 到 以 30 分钟为间隔。之后,JavaScript 必须根据列 () 和时间(例如 ,等)将该 JSON 数据提取到该表中。07:00 AM07:00 PMdayOfWeek07:00 AM - 07:30 AM

由于存在持续时间较长的调度 ( ),因此必须使用 attribute 合并获取数据的行,以防止 和 中相同数据的重复。07:00 AM - 10:00 AMMONDAYrowspanStart timeEnd Time

我的问题是它不会将数据提取到 HTML 表中。我尝试在(浏览器的)控制台选项卡中获取数据并显示 JSON,但它没有显示在表上。

下面是 JavaScript:

function calculateRowspan(cellData, day, dayData) {
  let rowspan = 1;
  const timeText = cellData["time"];

  // Iterate through subsequent rows to check for matching details
  const currentIndex = dayData.indexOf(cellData);
  for (let i = currentIndex + 1; i < dayData.length; i++) {
    if (dayData[i]["time"] === timeText && dayData[i]["status"] === cellData["status"]) {
      rowspan++;
    } else {
      break;
    }
  }

  return rowspan;
}

$(document).ready(function() {
  function generateTimeSlots() {
    const startTime = new Date(0, 0, 0, 7, 0, 0); // Set start time to 7:00 AM
    const endTime = new Date(0, 0, 0, 19, 0, 0); // Set end time to 7:00 PM
    const interval = 30 * 60 * 1000; // 30 minutes in milliseconds

    const tableBody = document.querySelector("tbody");
    const daysOfWeek = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];

    // Clear existing table content
    tableBody.innerHTML = '';

    for (let currentTime = startTime; currentTime < endTime; currentTime.setTime(currentTime.getTime() + interval)) {
      const row = document.createElement("tr");
      const timeText = currentTime.toLocaleTimeString([], {
          hour: '2-digit',
          minute: '2-digit'
        }) +
        " - " +
        new Date(currentTime.getTime() + interval).toLocaleTimeString([], {
          hour: '2-digit',
          minute: '2-digit'
        });

      row.innerHTML = '<td>' + timeText + '</td>' + new Array(7).fill('<td></td>').join('');
      tableBody.appendChild(row);
    }

    // Fetch class schedule data from the PHP script using AJAX
    $.ajax({
      url: "get-class-schedule.php",
      type: "GET",
      dataType: "json",
      success: function(data) {
        console.log("Data fetched successfully:", data);

        // Iterate through the received data and populate the table cells
        data.forEach(function(dayData, index) {
          const day = daysOfWeek[index];

          // Check if the array for the current day is empty
          if (dayData[day].length > 0) {
            dayData[day].forEach(function(cellData) {
              const timeText = cellData["time"];
              const matchingRow = Array.from(tableBody.rows).find(row => row.cells[0].textContent === timeText);

              if (matchingRow) {
                const cell = matchingRow.cells[index + 1]; // Skip the first cell (Time)
                const rowspan = calculateRowspan(cellData, day, dayData[day]);

                if (rowspan > 1) {
                  cell.setAttribute("rowspan", rowspan);
                  rowspanMap[day] = rowspan - 1; // Set rowspan for subsequent rows
                }

                cell.innerHTML = cellData["status"].replace(/<br>/g, "\n"); // Replace <br> with line breaks
              }
            });
          }
        });
      },
      error: function(error) {
        console.error("Error fetching data:", error);
      },
      complete: function() {
        console.log("AJAX request completed.");
      },
    });
  }

  // Call the function to generate time slots immediately
  generateTimeSlots();
});

下面是 HTML 表格:

<div class="card-body">
  <div class="table-responsive">
    <table class="table table-bordered table-white">
      <thead>
        <tr>
          <th>Time</th>
          <th>Monday</th>
          <th>Tuesday</th>
          <th>Wednesday</th>
          <th>Thursday</th>
          <th>Friday</th>
          <th>Saturday</th>
          <th>Sunday</th>
        </tr>
      </thead>
      <tbody class="small">
        <!-- JavaScript will populate time slots here -->
      </tbody>
    </table>
  </div>
</div>

最后,示例 JSON 数据:

[
  {
    "Monday": [
      {
        "time": "07:00 AM - 08:00 AM",
        "status": "In"
      },
      {
        "time": "08:00 AM - 10:00 AM",
        "status": "In Class<br>Subject 101<br>BA 1-2<br>Room 3"
      },
      {
        "time": "10:00 AM - 12:00 PM",
        "status": "In Class<br>Subject 11<br>BA 1-2<br>Room 1"
      },
      {
        "time": "12:00 PM - 02:00 PM",
        "status": "In"
      },
      {
        "time": "02:00 PM - 04:00 PM",
        "status": "Consultation"
      },
      {
        "time": "04:00 PM - 07:00 PM",
        "status": "In Class<br>Subject 1<br>BA 1-2<br>Room 2"
      }
    ]
  }
]

期待您的建议。

javascript jquery json ajax html-table

评论

0赞 Swati 11/16/2023
给定代码中的几个问题,即:1。这些值没有附加 AM/PM。2.当您将第一个tds值与此值进行比较时,将永远不会匹配,因为您的时间从后端返回的时间是分钟,即:所以值永远不会为真。timeTexttimeText> 3008:00 AM - 10:00 AMmatchingRow

答: 暂无答案