简体   繁体   English

从AJAX更新HTML

[英]Update HTML from AJAX

My table is appended to instead of updated. 我的表被附加到而不是更新。 What would be the appropriate way to update the html. 什么是更新html的适当方法。 I tried to use the answer from a similar stackoverflow question but it didn't work. 我试图使用类似的stackoverflow问题答案,但是没有用。

Here's my webpage, which uses Bootstrap, and the relevant ajax: 这是我的网页,该网页使用Bootstrap和相关的Ajax:

<div class="bs-component">
  <table class="table table-striped table-hover ">
      <thead>
      <tr>
          <th style="font-size: 25px">Week <span id="week" style="font-size: 28px">1</span></th>
          <th>12 am - 8 am</th>
          <th>8 am - 12 pm</th>
          <th>12 pm - 4 pm</th>
          <th>4 pm - 8 pm</th>
          <th>8 pm - 12 am</th>

      </tr>
      </thead>
      <tbody>
          <script>
          function loadWeek (x) {
            $.post("weekly.php", {p: x}, function (res) {
               //$("tbody").append(res);
               $('#bs-component table > tbody:last').find('tr:first').before(res);
            });
          }
          $(function () {
            loadWeek (1);
          });
          </script>
      </tbody>
  </table>

Here's the html echoed by the php called by ajax 这是由ajax调用的php回显的html

for ($i = 0; $i < 7; $i++) {
    echo "<tr><td>$weekDays[$i]</td>";
    for ($j = 0; $j < 5; $j++) {
        echo "<td><p>".$usersNames[$i][$j]."</p></td>";
    }
    echo"</tr>";
}

I see a few small issues with your jQuery code. 我发现您的jQuery代码有一些小问题。 First, you want to move the <script> tag out of the table. 首先,您要将<script>标记移出表格。 It can be anywhere in the page, and typically goes at the bottom of the page (just before the closing body tag </body> ). 它可以在页面中的任何位置,通常位于页面底部(紧接在结束body标记</body> )。 The reason you want to do this is that when the Ajax response returns, you want to replace the contents of the <tbody> which will overwrite your <script> tag. 这样做的原因是,当Ajax响应返回时,您想要替换<tbody>的内容,这将覆盖您的<script>标记。

Next, what you want to do with the response is replace the contents of the <tbody> (rather than append). 接下来,您要对响应执行的操作是替换<tbody>的内容(而不是追加)。 I would rewrite your loadWeek function as follows: 我将重写您的loadWeek函数,如下所示:

function loadWeek(x) {
  $.post('weekly.php', {p: x}, function(res) {
    $('#bs-component tbody').html(res);
  });
}

You can find the documentation for the .html() function at https://api.jquery.com/html/ 您可以在https://api.jquery.com/html/上找到.html()函数的文档。

Notice the selector is slightly different - because you only have 1 <table> inside your <div> , and that table only has 1 <tbody> inside that table, you don't have to specify the last <tbody> that is a direct descendant of a <table> (which is what the selector you have means). 请注意,选择器略有不同-因为您的<div>只有1个<table> ,并且该表中只有1个<tbody> ,因此不必指定最后一个直接的<tbody> <table>后代(这是您具有的选择器的意思)。

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

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