【问题标题】:HTML code not working when created by AJAX insert由 AJAX 插入创建时 HTML 代码不起作用
【发布时间】:2021-08-22 21:56:06
【问题描述】:

我正在使用 AJAX 调用一个 PHP 文件,该文件从 MySQL 数据库中提取调用摘要。然后,AJAX 例程将返回的表格以及表格中每一行的 HTML 表单插入到原始网页中。每行都有一个提交按钮,用于打开实际记录并显示所有信息,以便对其进行编辑。当我在没有 AJAX 更新的情况下仅在 HTML 中编写代码时,它可以完美运行,但我需要刷新网页以更新数据。我希望数据每 5 秒自动刷新一次,而无需刷新整个页面。当我将代码移至 AJAX 例程时,表格与数据和每行的提交按钮完美结合,但提交按钮不执行任何操作。

在主 HTML 页面中调用 AJAX 例程的代码

const interval = setInterval(function() {
  const xhttp = new XMLHttpRequest();
  xhttp.onload = function() {
    document.getElementById("unitstatus").innerHTML = this.responseText;
  }
xhttp.open("GET", "updatestatus.php");
xhttp.send(); 
}, 5000);

在主 HTML 页面中显示响应的代码

<div id='unitstatus' name='unitstatus'></div>

AJAX 调用的 PHP 文件

<?php

session_start();
$event = $_SESSION['event'];

set_include_path('./includes/');
include 'conn.inc';

$conn = new mysqli($servername, $username, $password, $dbname);
$sql="SELECT * from sags WHERE Complete='N' AND event='$event' ORDER BY bib";

?>
<!DOCTYPE html >
<head>
    <script src="https://code.jquery.com/jquery-2.1.4.js"></script>
</head>
<body>
    <table width='100%' border='1'>
        <tr>
            <td width='100%' height='45px' colspan='8' class='w3-center'>
                <button class='w3-button w3-blue w3-text-white w3-medium w3-padding-8' name='addnew' id='addnew' onclick='gotonewcall()'>ADD NEW REQUEST</button>
            </td>
        </tr>
        <tr>
            <td width='6%' class='w3-padding-small w3-small'><b>ID</b></td>
            <td width='14%' class='w3-padding-small w3-small'><b>NAME</b></td>
            <td width='6%' class='w3-padding-small w3-small'><b>BIB</b></td>
            <td width='12%' class='w3-padding-small w3-small'><b>CELL PHONE</b></td>
            <td width='24%' class='w3-padding-small w3-small'><b>CALL</b></td>
            <td width='18%' class='w3-padding-small w3-small'><b>LAST UPDATE</b></td>
            <td width='15%' class='w3-padding-small w3-small'><b>STATUS</b></td>
            <td width='5%'></td>
        </tr>
        <?php
            if(mysqli_query ($conn, $sql)){
            $result = mysqli_query ($conn, $sql);
            while($row=mysqli_fetch_array($result)){
                if ($row['status']=="ONLOCATION"){
                    $status = "ON LOCATION";
                } else {
                    $status = $row['status'];
                }
        ?>
        <form action="editrequest.php" method="post">"
            <tr>
                
                <td width='6%' class='w3-padding-small w3-small w3-text-black'><b><?php echo $row['id'] ?><input type='text' name='id' id='id' style='width:100%' class='w3-light-gray' value=<?php echo $row['id'] ?> hidden></b></td>
                
                <td width='14%' class='w3-padding-small w3-small w3-text-black'><b><?php echo $row['fName'] ?></b></td>
                <td width='6%' class='w3-padding-small w3-small w3-text-black'><b><?php echo $row['bib'] ?></b></td>
                <td width='12%' class='w3-padding-small w3-small w3-text-black'><b><?php echo $row['cellphone'] ?></b></td>
                <td width='24%' class='w3-padding-small w3-small w3-text-black'><b><?php echo $row['sagrequest'] ?></b></td>
                <td width='18%' class='w3-padding-small w3-small w3-text-black'><b><?php echo $row['statstime'] ?></b></td>
                <?php
                    if ($status == "ON LOCATION"){
                        echo "<td width='15%' class='w3-padding-small w3-small w3-text-white w3-red'>";
                        echo "<b>" . $status . "</b>";
                        echo "</td>";
                    } elseif ($status == "ENROUTE"){
                        echo "<td width='15%' class='w3-padding-small w3-small w3-text-black w3-yellow'>";
                        echo "<b>" . $status . "</b>";
                        echo "</td>";
                    } elseif ($status == "NEW"){
                        echo "<td width='15%' class='w3-padding-small w3-small w3-text-black w3-white'>";
                        echo "<b>" . $status . "</b>";
                        echo "</td>";
                    } elseif ($status == "RECEIVED"){
                        echo "<td width='15%' class='w3-padding-small w3-small w3-text-black w3-gray'>";
                        echo "<b>" . $status . "</b>";
                        echo "</td>";
                    } elseif ($status == "TRANSPORTING"){
                        echo "<td width='15%' class='w3-padding-small w3-small w3-text-white w3-purple'>";
                        echo "<b>" . $status . "</b>";
                        echo "</td>";
                    }
                ?>
                <td width='5%' class='W3-center w3-tiny'>
                    <input type="submit" value="OPEN" name="editentry" id="editentry" class="w3-button w3-blue w3-center" style="width:100%; height:100%">
                </td>
            </tr>   
        </form>
        <?php
                }
            } else {
                echo "<tr><td colspan='8' class='w3-center'><h3><b>NO ACTIVE CALLS</b></h3></td></tr>";
            }
        ?>
        </table>
        <?php
            mysqli_close();
        ?>

【问题讨论】:

  • 从服务器端渲染的资源中获取一些“HTML”是一个过时的原则。您最好获取一些 JSON 数据,并从返回的数据构建 HTML,即:在客户端上。这样您就可以创建一个可重用的 API 而无需关心响应标记,但您会知道它使用的是标准化的 JSON 数据。
  • 什么确切不起作用?你有什么努力让它发挥作用?这与 JS、PHP 或 AJAX 有关吗?

标签: javascript php html jquery ajax


【解决方案1】:

我会做这样的事情,工作示例here。

PHP 文件

<?php
    session_start();
    $event = $_SESSION['event'];
    
    set_include_path('./includes/');
    include 'conn.inc';
    
    $conn = new mysqli($servername, $username, $password, $dbname);
    
    $sql="SELECT * from sags WHERE Complete='N' AND event='$event' ORDER BY bib";
                if(mysqli_query ($conn, $sql)){
                $result = mysqli_query ($conn, $sql);
                while($row=mysqli_fetch_array($result)){
                    if ($row['status']=="ONLOCATION"){
                        $status = "ON LOCATION";
                    } else {
                        $status = $row['status'];
                    }
            ?>
            
                <tr>
                    
                    <td width='6%' class='w3-padding-small w3-small w3-text-black'><b><?php echo $row['id'] ?>
                     </b></td>
                    
                    <td width='14%' class='w3-padding-small w3-small w3-text-black'><b><?php echo $row['fName'] ?></b></td>
                    <td width='6%' class='w3-padding-small w3-small w3-text-black'><b><?php echo $row['bib'] ?></b></td>
                    <td width='12%' class='w3-padding-small w3-small w3-text-black'><b><?php echo $row['cellphone'] ?></b></td>
                    <td width='24%' class='w3-padding-small w3-small w3-text-black'><b><?php echo $row['sagrequest'] ?></b></td>
                    <td width='18%' class='w3-padding-small w3-small w3-text-black'><b><?php echo $row['statstime'] ?></b></td>
                    <?php
                        if ($status == "ON LOCATION"){
                            echo "<td width='15%' class='w3-padding-small w3-small w3-text-white w3-red'>";
                            echo "<b>" . $status . "</b>";
                            echo "</td>";
                        } elseif ($status == "ENROUTE"){
                            echo "<td width='15%' class='w3-padding-small w3-small w3-text-black w3-yellow'>";
                            echo "<b>" . $status . "</b>";
                            echo "</td>";
                        } elseif ($status == "NEW"){
                            echo "<td width='15%' class='w3-padding-small w3-small w3-text-black w3-white'>";
                            echo "<b>" . $status . "</b>";
                            echo "</td>";
                        } elseif ($status == "RECEIVED"){
                            echo "<td width='15%' class='w3-padding-small w3-small w3-text-black w3-gray'>";
                            echo "<b>" . $status . "</b>";
                            echo "</td>";
                        } elseif ($status == "TRANSPORTING"){
                            echo "<td width='15%' class='w3-padding-small w3-small w3-text-white w3-purple'>";
                            echo "<b>" . $status . "</b>";
                            echo "</td>";
                        }
                    ?>
                    <td width='5%' class='W3-center w3-tiny'>
                        <form action="editrequest.php" method="post">
                        <input type='text' name='id' id='id' style='width:100%' class='w3-light-gray' value=<?php echo $row['id'] ?> hidden>
                        <input type="submit" value="OPEN" name="editentry" id="editentry" class="w3-button w3-blue w3-center" style="width:100%; height:100%">
                     </form>
                    </td>
                </tr>   
            <?php
                    }
                } else {
                    echo "<tr><td colspan='8' class='w3-center'><h3><b>NO ACTIVE CALLS</b></h3></td></tr>";
                }
            ?>

JavaScript

const interval = setInterval(function() {
  $("#tableForm").load("updatestatus.php");//Load since just updating data
//You can use $.get() as well
//Or use $.post() if you have some data to send to php file.
//and append response with .html()
}, 5000);

HTML

<!DOCTYPE html >
<head>
    <script src="https://code.jquery.com/jquery-2.1.4.js"></script>
</head>
<body>
    <table width='100%' border='1'>
        <tr>
            <td width='100%' height='45px' colspan='8' class='w3-center'>
                <button class='w3-button w3-blue w3-text-white w3-medium w3-padding-8' name='addnew' id='addnew' onclick='gotonewcall()'>ADD NEW REQUEST</button>
            </td>
        </tr>
        <tr>
            <td width='6%' class='w3-padding-small w3-small'><b>ID</b></td>
            <td width='14%' class='w3-padding-small w3-small'><b>NAME</b></td>
            <td width='6%' class='w3-padding-small w3-small'><b>BIB</b></td>
            <td width='12%' class='w3-padding-small w3-small'><b>CELL PHONE</b></td>
            <td width='24%' class='w3-padding-small w3-small'><b>CALL</b></td>
            <td width='18%' class='w3-padding-small w3-small'><b>LAST UPDATE</b></td>
            <td width='15%' class='w3-padding-small w3-small'><b>STATUS</b></td>
            <td width='5%'></td>
        </tr>
        <div id="tableForm"><!-- I will load form here from php --></div>
</table>

编辑:-

说明

在我看到&lt;form .....&gt; ... 但没有&lt;/form&gt; 的inspect 元素中,我尝试了很多方法以使其成为明确定义的表单,但失败了。您的代码的某些部分破坏了输入元素,因此我单独声明了它,因为表单只有 1 个输入。

建议

  1. 仅从 ajax 请求的文件中回显所需的代码。
  2. 为什么要避免使用&lt;b&gt;? idk 但最好使用font-weight:bold
  3. 使用 $.ajax() $.post() $.get() 更简单的方式来处理 AJAX 请求。

【讨论】:

  • 请为您的答案添加一些解释。你改变了什么,为什么?请记住,解释有助于其他人理解您的答案并从中学习
  • 这个答案看起来有点简单,所以我先试了一下,效果很好。谢谢!
【解决方案2】:

因为您要向 DOM 添加新元素,所以您需要为每个新添加的按钮注册事件处理程序。

但是,您可以使用另一种方法是在表本身上仅注册一次事件侦听器并捕获源自按钮的事件:

const templ = document.getElementById("templ").content;
const result = document.getElementById("result");

//event listener on parent
document.getElementById("table2").addEventListener("click", buttonClicked2);

function add(parent, addEvent)
{
  parent = document.getElementById(parent);
  const row = templ.cloneNode(true);
  row.querySelector("td").textContent = "row " + (parent.children.length+1);
  //event listener on button
  if (addEvent)
    row.querySelector("button").addEventListener("click", buttonClicked);

  parent.tBodies[0].appendChild(row);
}

function buttonClicked(e) {
  result.textContent = "table=" + e.target.parentNode.offsetParent.id + " row=" + e.target.parentNode.parentNode.rowIndex;
}

function buttonClicked2(e) {

  result.textContent = e.target.tagName; //this will show which element clicked unless button was clicked

  if (e.target.tagName != "BUTTON")
    return;

  result.textContent = "table=" + e.target.parentNode.offsetParent.id + " row=" + e.target.parentNode.parentNode.rowIndex;
}
.flex {
  grid-gap: 1em;
  display: flex;
}
Clicked button at <span id="result"></span>
<div class="flex">
  <div>Events from button 
    <button onclick="add('table1', true)">Insert</button>
    <table id="table1">
      <thead><tr><th>col1</th><th>col2</th></tr></thead>
      <tbody></tbody>
    </table>
  </div>
  <div>Events from table 
    <button onclick="add('table2', false)">Insert</button>
    <table id="table2">
      <thead><tr><th>col1</th><th>col2</th></tr></thead>
      <tbody></tbody>
    </table>
  </div>
  <template id="templ"><tr><td></td><td><button>click me</button></td></tr></template>
</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-19
    • 2022-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-31
    • 1970-01-01
    相关资源
    最近更新 更多