一套简单的无刷新数据增删改查功能,基于jQuery Ajax异步请求技术,后端使用PHP处理数据并返回结果给前端,实现页面无刷新,不跳转对数据增删改查操作。
index.html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>AJAX 无刷新增删改查</title>
<!-- 引入 jQuery -->
<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
<style>
* {
margin: 20px;
font-family: Arial;
}
.item {
padding: 10px;
border: 1px solid #ccc;
margin: 5px 0;
}
button {
cursor: pointer;
padding: 3px 8px;
}
</style>
</head>
<body>
<h2>AJAX 无刷新增删改查</h2>
<!-- 添加表单 -->
<div>
<input type="text" id="name" placeholder="输入内容">
<button id="addBtn">添加</button>
</div>
<!-- 数据列表 -->
<div id="list"></div>
<script>
// 页面加载时获取数据列表
$(function() {
getList();
});
// 获取数据列表
function getList() {
$.get("api.php?action=getList", function(res) {
$("#list").html(res); // 从api.php获取数据渲染到页面
});
}
// 添加数据
$("#addBtn").click(function() {
let name = $("#name").val();
if (!name) return alert("请输入内容");
$.post("api.php", {
action: "add",
name: name
}, function() {
$("#name").val(""); // 清空输入框
getList(); // 重新加载列表
});
});
// 删除数据
$(document).on("click", ".delBtn", function() {
let id = $(this).data("id");
if (!confirm("确定删除?")) return;
$.post("api.php", {
action: "del",
id: id
}, function() {
getList(); // 更新列表
});
});
// 修改数据
$(document).on("click", ".editBtn", function() {
let id = $(this).data("id");
let oldName = $(this).data("name");
let newName = prompt("修改内容", oldName);
if (!newName) return;
$.post("api.php", {
action: "edit",
id: id,
name: newName
}, function() {
getList(); // 更新列表
});
});
</script>
</body>
</html>
api.php
<?php
// 数据存储文件
$file = "data.txt";
// 获取操作方法
$action = $_GET["action"] ?? $_POST["action"];
// 读取所有数据
function getDatas(){
global $file;
return is_file($file) ? json_decode(file_get_contents($file), true) : [];
}
// 保存数据
function saveDatas($datas){
global $file;
file_put_contents($file, json_encode($datas, JSON_UNESCAPED_UNICODE));
}
// 获取数据列表
if($action == "getList"){
$list = getDatas();
if(empty($list)){
echo "暂无数据";
exit;
}
foreach($list as $id => $name){
echo "
<div class='item'>
ID:{$id} | 内容:{$name}
<button class='editBtn' data-id='{$id}' data-name='{$name}'>修改</button>
<button class='delBtn' data-id='{$id}'>删除</button>
</div>";
}
exit;
}
// 添加数据
if($action == "add"){
$name = $_POST["name"];
$list = getDatas();
$id = time(); // 用时间戳当唯一 ID
$list[$id] = $name;
saveDatas($list);
exit("ok");
}
// 删除数据
if($action == "del"){
$id = $_POST["id"];
$list = getDatas();
unset($list[$id]);
saveDatas($list);
exit("ok");
}
// 修改数据
if($action == "edit"){
$id = $_POST["id"];
$name = $_POST["name"];
$list = getDatas();
$list[$id] = $name;
saveDatas($list);
exit("ok");
}
本站原创内容,转载请注明来源:https://www.liutonghui.com/112.html
评论列表(0条)
暂无评论