[英]how to show loading animation and disable button during ajax process
我正在使用 ajax 将按钮的 id 发送到 test.php,但我被困在如何在 ajax 过程中禁用按钮和显示处理图像 gif 的步骤,
当我使用我的代码时,它只会禁用和隐藏第一个表格行按钮,而不是单击的特定按钮
我的代码是这样的
<tbody>
<?php
$letter=mysqli_query($con,"SELECT * FROM letters order by id DESC");
if(mysqli_num_rows($letter)>0){
while($rows_letter=mysqli_fetch_array($letter))
{
$id=$rows_letter['id'];
$subject=$rows_letter['subject'];
$status=$rows_letter['status'];
?>
<tr>
<th class="text-center" scope="row">1</th>
<td class="text-center"><?php echo $subject ;?></td>
<td class="text-center"><?php if($status == 1){echo '<mark style="background-color: #5cb85c; color:white;" > Successfully Sent </mark>'; }else{ echo '<mark style="background-color:#f0ad4e; color:white;"> Not Sent Yet </mark>';}?></td>
<td><button type="button" class="btn btn-info btn-sm btn-block">
<span class="fa fa-pencil-square-o"></span> Edit</button></td>
<td><button type="button" class="btn btn-danger btn-sm btn-block"> <span class="fa fa-trash-o"></span> Move To Trash</button></td>
<td>
<img src="https://svc.opushealth.com/balcoltrasavings/img/Processing.gif" id="img" style="display:none"/>
<button type="button" onclick="startsend(<?php echo $id;?>);"
id="id" value="<?php echo $id;?>"class="btn btn-success btn-sm btn-block">
<span class="fa fa-paper-plane-o"></span> Send To All</button></td>
</tr>
<?php
}
}
?>
</tbody>
<script type='text/javascript'>
//AJAX function
function startsend(id) {
$('#img').show();
$("#id").attr("disabled", true);
$.ajax({
type: "POST",
url: "test.php",
data:{ id: id },
success: function(msg){
alert( "Button Id is " + msg );
$('#img').hide();
}
});
}
</script>
test.php 文件是
<?php
if(isset($_POST['id'])){
$id = $_POST['id'];}
///rest process
?>
首先,您需要删除您在 PHP 循环内的 HTML 中创建的任何id
属性,因为这会创建无效的重复项。 而是将它们更改为类。
其次,使用不显眼的事件处理程序附加您的事件,而不是内联事件处理程序,因为它们已经过时且实践不佳。 当您使用 jQuery 时,这可以通过click()
或on()
方法来完成。
最后,在那个不显眼的事件处理程序中,您可以使用this
关键字来引用引发事件的元素并根据需要对其进行修改。 尝试这个:
<img src="https://svc.opushealth.com/balcoltrasavings/img/Processing.gif" class="img" style="display: none" />
<button type="button" value="<?php echo $id;?>" class="id btn btn-success btn-sm btn-block">
<span class="fa fa-paper-plane-o"></span>
Send To All
</button>
$('button.id').on('click', function() {
var $btn = $(this).prop("disabled", true);
var $img = $btn.prev('.img').show();
$.ajax({
type: "POST",
url: "test.php",
data: { id: $btn.val() },
success: function(msg) {
console.log("Button Id is " + msg);
$img.hide();
}
});
});
如果您正在使用 ajax,那么(使其尽可能简单)。
将您的加载 gif 图像添加到 html 并使其隐藏(现在使用 html 本身的样式,您可以将其添加到单独的 CSS):-
<img src="path\to\loading\gif" id="img" style="display:none"/ >
单击按钮时显示图像并在成功功能时再次隐藏它。
$('#buttonID').click(function(){
$('#img').show(); //<----show here
$.ajax({
....
success:function(result){
$('#img').hide(); //<--- hide again
}
}
确保你也隐藏了 ajax 错误回调中的图像,以确保即使 ajax 失败也隐藏 gif。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.