php ajax实现增删改查,###实现ajax的增删改查案例(jquery)
时间: 2023-07-14 10:11:57 浏览: 147
以下是一个使用 jQuery 实现增删改查的案例:
HTML 代码:
```html
<!DOCTYPE html>
<html>
<head>
<title>AJAX CRUD Example with jQuery</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@9"></script>
</head>
<body>
<h2>Users</h2>
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>Action</th>
</tr>
</thead>
<tbody id="user-list">
</tbody>
</table>
<h2>Add User</h2>
<form id="add-user-form">
<label>Name</label>
<input type="text" name="name">
<br>
<label>Email</label>
<input type="email" name="email">
<br>
<button type="submit">Add User</button>
</form>
<h2>Edit User</h2>
<form id="edit-user-form">
<input type="hidden" name="id">
<label>Name</label>
<input type="text" name="name">
<br>
<label>Email</label>
<input type="email" name="email">
<br>
<button type="submit">Update User</button>
</form>
<script src="script.js"></script>
</body>
</html>
```
JavaScript 代码:
```javascript
$(document).ready(function() {
// 显示用户列表
showUsers();
// 添加用户
$('#add-user-form').submit(function(e) {
e.preventDefault();
var name = $('input[name="name"]').val();
var email = $('input[name="email"]').val();
$.ajax({
method: 'POST',
url: 'api/user/create.php',
data: {
name: name,
email: email
},
success: function(response) {
showUsers();
Swal.fire({
title: 'Success',
text: 'User created successfully',
icon: 'success',
confirmButtonText: 'OK'
});
},
error: function(xhr, status, error) {
console.log(xhr);
console.log(status);
console.log(error);
}
});
});
// 显示编辑用户表单
$('#user-list').on('click', '.edit-user-button', function() {
var id = $(this).data('id');
var name = $(this).data('name');
var email = $(this).data('email');
$('input[name="id"]').val(id);
$('input[name="name"]').val(name);
$('input[name="email"]').val(email);
$('#edit-user-form').show();
});
// 更新用户
$('#edit-user-form').submit(function(e) {
e.preventDefault();
var id = $('input[name="id"]').val();
var name = $('input[name="name"]').val();
var email = $('input[name="email"]').val();
$.ajax({
method: 'POST',
url: 'api/user/update.php',
data: {
id: id,
name: name,
email: email
},
success: function(response) {
showUsers();
Swal.fire({
title: 'Success',
text: 'User updated successfully',
icon: 'success',
confirmButtonText: 'OK'
});
},
error: function(xhr, status, error) {
console.log(xhr);
console.log(status);
console.log(error);
}
});
});
// 删除用户
$('#user-list').on('click', '.delete-user-button', function() {
var id = $(this).data('id');
$.ajax({
method: 'POST',
url: 'api/user/delete.php',
data: {
id: id
},
success: function(response) {
showUsers();
Swal.fire({
title: 'Success',
text: 'User deleted successfully',
icon: 'success',
confirmButtonText: 'OK'
});
},
error: function(xhr, status, error) {
console.log(xhr);
console.log(status);
console.log(error);
}
});
});
// 显示用户列表
function showUsers() {
$.ajax({
method: 'GET',
url: 'api/user/read.php',
success: function(response) {
var users = JSON.parse(response);
var html = '';
users.forEach(function(user) {
html += '<tr>';
html += '<td>' + user.id + '</td>';
html += '<td>' + user.name + '</td>';
html += '<td>' + user.email + '</td>';
html += '<td>';
html += '<button class="edit-user-button" data-id="' + user.id + '" data-name="' + user.name + '" data-email="' + user.email + '">Edit</button>';
html += '<button class="delete-user-button" data-id="' + user.id + '">Delete</button>';
html += '</td>';
html += '</tr>';
});
$('#user-list').html(html);
},
error: function(xhr, status, error) {
console.log(xhr);
console.log(status);
console.log(error);
}
});
}
});
```
PHP 代码:
```
// api/user/create.php
<?php
header('Content-Type: application/json');
// 连接数据库
$servername = 'localhost';
$username = 'root';
$password = '';
$dbname = 'example';
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die('Connection failed: ' . $conn->connect_error);
}
// 获取 POST 数据
$name = $_POST['name'];
$email = $_POST['email'];
// 插入数据
$sql = 'INSERT INTO users (name, email) VALUES ("' . $name . '", "' . $email . '")';
if ($conn->query($sql) === TRUE) {
echo json_encode(array('message' => 'User created successfully'));
} else {
echo json_encode(array('error' => 'Error: ' . $sql . '<br>' . $conn->error));
}
$conn->close();
?>
// api/user/read.php
<?php
header('Content-Type: application/json');
// 连接数据库
$servername = 'localhost';
$username = 'root';
$password = '';
$dbname = 'example';
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die('Connection failed: ' . $conn->connect_error);
}
// 查询数据
$sql = 'SELECT * FROM users';
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$users = array();
while($row = $result->fetch_assoc()) {
$users[] = $row;
}
echo json_encode($users);
} else {
echo json_encode(array('message' => 'No users found'));
}
$conn->close();
?>
// api/user/update.php
<?php
header('Content-Type: application/json');
// 连接数据库
$servername = 'localhost';
$username = 'root';
$password = '';
$dbname = 'example';
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die('Connection failed: ' . $conn->connect_error);
}
// 获取 POST 数据
$id = $_POST['id'];
$name = $_POST['name'];
$email = $_POST['email'];
// 更新数据
$sql = 'UPDATE users SET name = "' . $name . '", email = "' . $email . '" WHERE id = ' . $id;
if ($conn->query($sql) === TRUE) {
echo json_encode(array('message' => 'User updated successfully'));
} else {
echo json_encode(array('error' => 'Error: ' . $sql . '<br>' . $conn->error));
}
$conn->close();
?>
// api/user/delete.php
<?php
header('Content-Type: application/json');
// 连接数据库
$servername = 'localhost';
$username = 'root';
$password = '';
$dbname = 'example';
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die('Connection failed: ' . $conn->connect_error);
}
// 获取 POST 数据
$id = $_POST['id'];
// 删除数据
$sql = 'DELETE FROM users WHERE id = ' . $id;
if ($conn->query($sql) === TRUE) {
echo json_encode(array('message' => 'User deleted successfully'));
} else {
echo json_encode(array('error' => 'Error: ' . $sql . '<br>' . $conn->error));
}
$conn->close();
?>
```
以上代码实现了使用 AJAX 和 jQuery 进行增删改查操作。其中,HTML 代码定义了用户列表和添加、编辑用户的表单,JavaScript 代码通过 AJAX 发送请求实现增删改查操作,PHP 代码处理请求并与数据库交互。同时,使用了 SweetAlert2 库来显示操作结果的提示框。
阅读全文