【问题标题】:jQuery Ajax loads the html data fine but the attribute seemed 'unreadable'jQuery Ajax 可以很好地加载 html 数据,但该属性似乎“不可读”
【发布时间】:2016-08-23 14:31:49
【问题描述】:

在我发疯之前请帮助我。 好的,所以我已经为我的代码苦苦挣扎了一个星期,但我仍然不知道什么不起作用。

我可以使用锚标记的 data-target 属性调用模式。我知道它工作正常。这是我的 PHP 文件。这也没有问题。

PHP (placement-load.php)

<?php
include 'connection.php';
$sql = "SELECT * FROM tbl_personal";
$r = mysqli_query($con,$sql);
$nr = mysqli_num_rows($r);
if($nr > 0) {
    while($dt = mysqli_fetch_array($r)){
        echo "
            <tr>
                <td>".$dt[0]."</td>
                <td><a data-target='#modalShowDetails'>Edit</a></td>
            </tr>
        ";
    }
}else {
    echo "";
}
?>

我有两种情况 如果我这样做:

<div class="table">
    <table>
        <thead>
            <tr>
                <th>Name</th>
                <th></th>
            </tr>
        </thead>
        <tbody id="placement-table">
            <?php include 'placement-load.php'; ?>
        </tbody>
    </table>
</div>

表格主体会很好地加载,如果我单击编辑(在锚标记中),模式也会加载。

但是!

如果我删除 tbody 标记中的包含并执行此操作(使用 jQuery Ajax):

$(document).ready(function() {
    autoRefresh();
});
function autoRefresh() {
    $.ajax( {
        method: 'POST',
        url: "php/placement-load.php",
        success: function(data) {
            $('#placement-table').html(data);
        }
    });
}

表格主体也可以正常加载,但如果我单击编辑(在锚标记中),模式将不起作用。

为什么?

【问题讨论】:

  • 我的猜测是,使用 ajax 方法,edit 的事件侦听器已经就位,而 ajax 拉入新内容为时已晚,无法为它们分配函数。
  • 编辑按钮在哪里?
  • @Mir 在 php 文件中 &lt;a data-target='#modalShowDetails'&gt;Edit&lt;/a&gt;

标签: javascript php jquery html ajax


【解决方案1】:

当您通过 ajax 加载数据时,这就是为什么已经与 DOM 中存在的 html 绑定的早期 jquery 无法处理添加到 DOM 中的新 html 元素。

在这种情况下,我们需要再次执行页面上已经执行的jQuery,以将它们与新添加的html绑定在一起。

我采用的方法是创建一个名为 bind 的函数并添加所有不再在其中工作的 jQuery 事件,并在文档的就绪事件上调用它,并在完成 ajax 调用时调用该函数。参见以下sn-p供参考:

function autoRefresh() {
    $.ajax( {
        method: 'POST',
        url: "php/placement-load.php",
        success: function(data) {
            $('#placement-table').html(data);
            bind(); //Calling bind function on ajax call success
        }
    });
}

//Define bind function
function bind(){
    //Add code to open the modal here
    //You can add all the jquery code which is not executing after loading the data from ajax
}

//calling bind() along with your autoRefresh function
$(document).ready(function() {
    autoRefresh();
    bind();
});

【讨论】:

    【解决方案2】:

    我想我明白了。我在 autoRefresh 函数中的 $('#placement-table').html(data) 正下方插入了 $.getScript("location of my script to open the modal here");。对此有什么想法吗?

    来源:https://api.jquery.com/jquery.getscript/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-10
      • 1970-01-01
      • 1970-01-01
      • 2014-06-14
      • 1970-01-01
      • 2022-08-04
      • 1970-01-01
      • 2021-12-07
      相关资源
      最近更新 更多