更新文档上的Ajax.准备功能

Update Ajax on Document.ready function

本文关键字:功能 Ajax 文档 更新      更新时间:2023-09-26

文档准备好后,我让页面调用ajax并显示结果表。

可以通过单击按钮更新行,然后该按钮调用将更新发布到服务器的函数。

我没有在document ready函数中包含click函数,但是一旦我将它们组合起来,它就不起作用了。

<div id="newreqs"></div>
Javascript

$(document).ready(function(){
    $('.approveCredit').on('click', function(e) {
        e.preventDefault();
        var creditid = $(this).attr('creditid');
        var allocatedcreds = $(this).attr('allocatedcreds');
        $.ajax({
            url: "assets/ajax/addcustomer.php",
            type: "POST",
            data: {creditid: creditid,allocatedcreds: allocatedcreds},
            success: function(result){
                alert('Credit Applied!');               
            },
            error: function(exception){
                alert('Exception:' +exception);
            }
        });
    });
    $.post('assets/ajax/calldata/newreqs.php', function(data) {
        $('#newreqs').html(data)
    });
});

数据叫做

<table class="table table-hover">
<thead>
<tr>
<th class="text-center" style="width: 50px;">#</th>
<th class="hidden-xs" style="width: 15%;">Name</th>
<th class="hidden-xs" style="width: 15%;">Requested Credits</th>
<th class="hidden-xs" style="width: 15%;">Notes from User</th>
<th class="hidden-xs" style="width: 15%;">PO</th>
<th class="hidden-xs" style="width: 15%;">Date Requested</th>
<th class="hidden-xs" style="width: 15%;">Status</th>
<th class="text-center" style="width: 15px;">Actions</th>
</tr>
</thead>
<tbody>
<?php 
  $count = 1;
    while ($row = mysql_fetch_array($test))  
    {?>
   <tr>
       <td class="text-center"><?php echo $count++;?></td>
       <td><?php echo $row['user_id'];?></td>
       <td><?php echo $row['credits'];?></td>
       <td><?php echo $row['notes'];?></td>
       <td><?php echo $row['po'];?></td>
       <td><?php echo $row['date_received'];?></td>
       <td><?php echo $status;?></td>
       <td class="text-center">
           <div class="btn-group">
               <a class="btn btn-xs btn-default approveCredit" type="button" allocatedcreds="<?php echo $row['credits'];?>" creditid="<?php echo $row['id'];?>" data-toggle="tooltip" data-original-title="Approve Credit Request"><i class="fa fa-check"></i></a>
           </div>
       </td>
    </tr> 
<?php } ?>  
</tbody>
</table>

如前所述,当我没有在document ready函数中封装click函数时,它可以工作,但是,当没有封装时,它可以工作。

我封装click函数的原因是因为我想在服务器上更新数据后创建一个页面刷新

这是一个事件委托的用例,修改为:

$(document).on('click', '.approveCredit', function(e) {

$(document)可以替换为静态父节点:

$('#newreqs').on('click', '.approveCredit', function(e) {

加载页面时,按钮不在那里,该元素的事件无法注册。因此,可以做的是将事件委托给静态父节点或document本身。