javascript - 无需页面刷新且无需单击按钮即可从数据库中获取数据 - AJAX PHP
问题描述
我正在我的网站上创建一个 CRUD 功能。我正在使用 Ajax 来立即加载数据,但它对我不起作用。
到目前为止,我看到他们需要单击一个按钮或设置一个时间间隔,但我不想要这个。我的代码有什么问题或缺少什么?
这就是我的 HTML 的样子
<div class="card-body">
<div id="blog_table">
</div>
</div>
<script>
$( document ).ready(function() {
$("#blog_table").load("functions/blog_list.php",{
});
});
</script>
我的 PHP 代码
<?php include "../../function.php";
$user_id = $_SESSION['id'];
$select_blogs = query("SELECT blog_id, blog_title, create_date FROM user_blog WHERE user_id = '{$user_id}'");
$result = confirm($select_blogs);
echo '<table class="table">
<thead>
<tr>
<th>Title</th>
<th>Date Creasdawsdated</th>
</tr>
</thead>';
if(row_count($select_blogs) > 0){
while($row = fetch_assoc($select_blogs)){
echo "<tr>
<td>".$row['blog_id']."</td>
<td>".$row['blog_title']."</td>
<td class='text-right py-0 align-middle'>
<div class='btn-group btn-group-sm'>
<button href='blog_view?id=".$row['blog_id']."'' class='btn btn-info'><i class='fas fa-eye'></i></button>
<button id='".$row['blog_id']."'' class='btn btn-danger' onclick='deleteFunction(this.id)'><i class='fas fa-trash'></i></button>
</div>
</td>
</tr>";
}
}
?>
每当我单击删除按钮时。它只是删除数据,但表不加载更改。
这是我的删除按钮的功能。
function deleteFunction(id) {
event.preventDefault();
var blog_id = id;
Swal.fire({
title: 'Are you sure you want to delete this blog?',
text: "You won't be able to revert this!",
icon: 'warning',
showCancelButton: true,
confirmButtonColor: '#d33',
cancelButtonColor: '#3085d6',
confirmButtonText: 'Yes, delete it!'
}).then((result) => {
if (result.isConfirmed) {
$.ajax({
method: 'POST',
data: {'delete': true, 'blog_id' : blog_id },
url: 'functions/blog_delete.php',
success: function(data) {
}
});
Swal.fire(
'Deleted!',
'Your blog has been deleted.',
'success'
)
}
})
}
删除函数的 PHP 文件。
<?php include "../../function.php";
$blog_id = escape_string($_POST['blog_id']);
$query = "DELETE FROM user_blog where blog_id = '{$blog_id}'";
$final_query = query($query);
confirm($final_query);
echo $final_query;
echo $query;
?>
解决方案
当您将.load()
函数添加到 时$(document).ready()
,您是在告诉 jQuery 加载页面一次- 在页面加载时,当文档准备好时。这意味着,在您再次运行该功能或刷新页面之前,它不会再次更新。
如果您想刷新数据,例如当您按下删除按钮时,请再次运行该功能,例如在您的deleteFunction()
.
推荐阅读
- java - 在 Koltin/Java 中,如何强制使用来自 Maven 依赖项的同名类覆盖本地项目类?
- php - 如何从同一服务器上的另一个域调用 php 文件
- java - 如果 value 是实例,则 TreeMap 按值排序
- c# - SquareUp 请求令牌:禁止
- java - 如何将 JSON 转换为 POJO 类?
- xamarin.ios - 如何将文件从临时位置复制到应用程序容器 - Xamarin iOS
- c - 将指向结构数组的指针设置为等于结构数组
- ruby - 是否有 Yard 的默认 Rake 任务
- firebase - Firebase 警告:身份验证为匿名的用户的权限被拒绝
- smtp - 解码 Nodemailer SMTP 响应