code Copy code
.topbar {
background-color: #343a40;
color: white;
padding: 15px 20px;
display: flex;
justify-content: space-between;
align-items: center;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
}
.topbar button {
background-color: #dc3545;
border: none;
color: white;
padding: 10px 15px;
border-radius: 20px;
cursor: pointer;
transition: background-color 0.3s, transform 0.3s;
font-weight: bold;
}
.topbar button:hover {
background-color: #c82333;
transform: scale(1.05);
}
.sidebar {
width: 240px;
background-color: #343a40;
color: white;
padding: 20px;
position: fixed;
top: 75px;
height: calc(100% - 75px);
overflow-y: auto;
box-shadow: 2px 0 10px rgba(0, 0, 0, 0.2);
}
.sidebar h1 {
text-align: center;
font-size: 24px;
margin-bottom: 20px;
font-weight: bold;
}
.sidebar button {
font-size: 16px;
width: 100%;
padding: 12px;
margin: 8px 0;
border: none;
border-radius: 8px;
background-color: #495057;
color: white;
cursor: pointer;
transition: background-color 0.3s;
}
.sidebar button:hover {
background-color: #5a6268;
}
.main-content {
margin-left: 240px;
padding: 25px;
flex-grow: 1;
background-color: #f8f9fa;
margin-top: 75px;
flex-direction: column;
align-items: center;
}
.section {
width: 100%;
max-width: 800px;
margin-bottom: 30px;
text-align: center;
/* background-color: white; */
border-radius: 10px;
/* 圆角 */
/* box-shadow: 0 2px 15px rgba(0, 0, 0, 0.1); */
padding: 20px;
}
.form-container {
padding: 20px;
margin: 0 auto;
}
.form-container input {
width: calc(100% - 30px);
padding: 15px;
border: 1px solid #ccc;
border-radius: 5px;
margin: 10px 0;
transition: border-color 0.3s;
}
.form-container input:focus {
border-color: #007bff;
outline: none;
}
.query-button {
padding: 12px 20px;
font-size: 16px;
border: none;
border-radius: 5px;
background-color: #007bff;
color: white;
cursor: pointer;
transition: background-color 0.3s, transform 0.3s;
}
.query-button:hover {
background-color: #0056b3;
transform: scale(1.05);
}
.search-results-container {
padding: 20px;
border-radius: 10px;
width: 100%;
margin-top: 20px;
}
.search-result-item {
background-color: white;
padding: 15px;
margin: 10px 0;
border-radius: 10px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
display: flex;
justify-content: space-between;
align-items: center;
}
.search-result-item div {
flex: 1;
margin-right: 20px;
}
.book-actions button {
background-color: #007bff;
color: white;
border: none;
padding: 10px 15px;
border-radius: 5px;
cursor: pointer;
transition: background-color 0.3s;
}
.book-actions button:hover {
background-color: #0056b3;
}
.book-list {
list-style-type: none;
padding: 0;
width: 100%;
}
.book-list li {
background-color: white;
padding: 15px;
margin: 10px 0;
border-radius: 10px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
display: flex;
justify-content: space-between;
align-items: center;
}
.book-list button {
background-color: #007bff;
padding: 8px 12px;
border: none;
border-radius: 4px;
color: white;
cursor: pointer;
transition: background-color 0.3s, transform 0.3s;
}
.book-list button:hover {
background-color: #0056b3;
transform: scale(1.05);
}
</style>
code Copy code
<script>
document.addEventListener("DOMContentLoaded", function () {
updateUsernameDisplay();
});
function logout() {
alert('已退出登录');
localStorage.removeItem('userInfo');
localStorage.removeItem('username');
updateUsernameDisplay();
window.location.href = 'login.html';
}
function updateUsernameDisplay() {
const username = localStorage.getItem('username');
const usernameDisplay = document.getElementById('username-display');
if (username) {
usernameDisplay.textContent = username;
} else {
usernameDisplay.textContent = '未登录';
console.log('在 localStorage 中未找到用户名');
}
}
function showSection(section) {
const sections = document.querySelectorAll('.section');
sections.forEach(s => s.style.display = 'none');
document.getElementById(section + 'Section').style.display = 'block';
if (section === 'favorites') {
loadFavorites();
} else if (section === 'history') {
loadBorrowHistory();
}
}
function searchBooks() {
const keyword = document.getElementById('searchInput').value.trim();
if (keyword === '') {
alert('请输入搜索关键词');
return;
}
// 移除特殊字符
const sanitizedKeyword = keyword.replace(/[%_]/g, '');
fetch('http://localhost:8080/api/books/search', {
method: 'POST',
headers: {
'Content-Type': 'application/json' // 声明使用 JSON 格式
},
body: JSON.stringify({ keyword }) // 将关键词封装成 JSON 发送到后端
})
.then(response => {
if (!response.ok) {
throw new Error('网络响应不正常');
}
return response.json(); // 解析 JSON 数据
})
.then(data => {
displaySearchResults(data); // 将结果显示在页面上
})
.catch(error => console.error('Error:', error)); // 处理异常情况
}
function displaySearchResults(books) {
const searchResults = document.getElementById('searchResults');
searchResults.innerHTML = ''; // 清空之前的结果
code Copy code
// 检查返回的书籍列表是否为空
if (books.length === 0) {
searchResults.innerHTML = '<p>没有找到相关书籍</p>'; // 提示用户未找到书籍
} else {
books.forEach(book => {
const listItem = document.createElement('div');
listItem.className = 'search-result-item';
listItem.innerHTML = `
<div>
<strong>书名:</strong> ${book.title}<br>
<strong>作者:</strong> ${book.author}<br>
<strong>出版年份:</strong> ${book.yearPublished || '未知'}
</div>
<div class="book-actions">
<button onclick="borrowBook(${book.id})">借阅</button>
<button onclick="addToFavorites(${book.id})">添加到收藏</button>
</div>
`;
searchResults.appendChild(listItem); // 将书籍信息添加到显示区域
});
}
}
function getUserId() {
const userInfo = JSON.parse(localStorage.getItem('userInfo'));
return userInfo ? userInfo.id : null;
}
function borrowBook(bookId) {
const userId = getUserId();
if (!userId) {
alert('用户信息已失效,请重新登录');
window.location.href = 'login.html';
return;
}
code Copy code
fetch('http://localhost:8080/api/borrow-records/borrow', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ userId: userId, bookId: bookId }) // 应该在请求体中传递用户和书籍的 ID
})
.then(response => {
if (!response.ok) {
throw new Error('网络响应不正常');
}
return response.json(); // 解析 JSON 数据
})
.then(data => {
alert('您已成功借阅');
loadBorrowHistory();
})
.catch(error => {
console.error('Error:', error);
alert('借阅书籍时发生错误,请稍后再试');
});
}
code Copy code
// 加载借阅历史
function loadBorrowHistory() {
const userId = getUserId();
if (!userId) {
alert('用户信息已失效,请重新登录');
window.location.href = 'login.html';
return;
}
// 更新 API 路径
fetch(`http://localhost:8080/api/borrow-records/user/borrow-history/${userId}`)
.then(response => {
if (!response.ok) {
throw new Error('未找到借阅记录');
}
return response.json();
})
.then(data => {
displayBorrowHistory(data);
})
.catch(error => {
console.error('Error:', error);
alert('加载借阅历史时发生错误,请稍后再试');
});
}
function displayBorrowHistory(borrowRecords) {
const borrowHistory = document.getElementById('borrowHistory');
borrowHistory.innerHTML = '';
code Copy code
if (borrowRecords.length === 0) {
borrowHistory.innerHTML = '<p>没有借阅记录</p>';
} else {
borrowRecords.forEach(record => {
const listItem = document.createElement('li');
const borrowDate = new Date(record.borrow_date || Date.now()); // 若 borrow_date 为 null, 使用当前时间
const formattedDate = borrowDate.toLocaleDateString('zh-CN', {
year: 'numeric',
month: '2-digit',
day: '2-digit'
});
listItem.textContent = `书名: ${record.title || '未知'} - 作者: ${record.author || '未知'} - 借阅日期: ${formattedDate} - 状态: ${record.is_returned ? '已还书' : '未还书'}`;
const returnButton = document.createElement('button');
returnButton.textContent = '还书';
returnButton.onclick = function () {
console.log('Attempting to return book with Record ID:', record.id);
returnBook(record.id, returnButton);
};
if (record.is_returned) {
returnButton.disabled = true;
returnButton.textContent = '已还书';
}
code Copy code
listItem.appendChild(returnButton);
borrowHistory.appendChild(listItem);
});
}
}
function returnBook(borrowRecordId, returnButton) {
const userId = getUserId();
if (!userId || !borrowRecordId) {
alert('无效的用户 ID 或借阅记录 ID');
return;
}
code Copy code
returnButton.disabled = true;
returnButton.textContent = '处理中...';
fetch(`http://localhost:8080/api/borrow-records/return/${borrowRecordId}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
}
})
.then(response => {
return response.text(); // 使用 .text() 解析文本响应
})
.then(data => {
console.log(data)
alert(data); // data 是字符串格式的消息
loadBorrowHistory(); // 重新加载借阅历史
})
.catch(error => {
console.error('Error:', error);
alert('还书时发生错误,请稍后再试');
returnButton.disabled = false;
returnButton.textContent = '还书'; // 恢复按钮状态
});
}
code Copy code
// 添加到收藏
function addToFavorites(bookId) {
const userId = getUserId();
if (!userId) {
alert('用户信息已失效,请重新登录');
window.location.href = 'login.html';
return;
}
fetch('http://localhost:8080/api/favorites/add', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ userId: userId, bookId: bookId }) // 确保这两个值非空
})
.then(response => {
if (!response.ok) {
return response.text().then(text => {
throw new Error('添加收藏时发生错误:' + text);
});
}
return response.json();
})
.then(data => {
alert('已成功添加到收藏!');
loadFavorites(); // 重新加载收藏列表
})
.catch(error => {
console.error('Error:', error);
alert('添加收藏时发生错误,请稍后再试');
});
}
code Copy code
// 加载收藏书籍
function loadFavorites() {
const userId = getUserId();
console.log('加载收藏的用户ID:', userId); // 增加调试信息
if (!userId) {
alert('用户信息已失效,请重新登录');
window.location.href = 'login.html';
return;
}
fetch(`http://localhost:8080/api/favorites/${userId}`)
.then(response => {
if (!response.ok) {
throw new Error('网络响应不正常');
}
return response.json();
})
.then(data => {
displayFavorites(data); // 确保数据结构正确
})
.catch(error => {
console.error('Error:', error);
alert('加载收藏时发生错误,请稍后再试');
});
}
code Copy code
// 显示收藏书籍
function displayFavorites(favoriteBooks) {
const favoritesList = document.getElementById('favoritesList');
favoritesList.innerHTML = '';
if (favoriteBooks.length === 0) {
favoritesList.innerHTML = '<p>没有收藏的书籍</p>';
} else {
favoriteBooks.forEach(favorite => {
const listItem = document.createElement('li');
listItem.innerHTML = `书名: ${favorite.bookTitle} - 作者: ${favorite.bookAuthor}`; // 使用 DTO 中的属性
const borrowButton = document.createElement('button');
borrowButton.textContent = '借阅';
borrowButton.onclick = function () {
borrowFromFavorites(favorite.bookId); // 使用书籍 ID
};
const deleteButton = document.createElement('button');
deleteButton.textContent = '删除收藏';
deleteButton.onclick = function () {
removeFromFavorites(favorite.bookId); // 使用书籍 ID
};
listItem.appendChild(borrowButton);
listItem.appendChild(deleteButton);
favoritesList.appendChild(listItem);
});
}
}
code Copy code
// 从收藏中借阅书籍
function borrowFromFavorites(bookId) {
const userId = getUserId();
if (!userId) {
alert('用户信息已失效,请重新登录');
window.location.href = 'login.html';
return;
}
fetch('http://localhost:8080/api/borrow-records/borrow', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ userId: userId, bookId: bookId }) // 将用户 ID 和书籍 ID 传递
})
.then(response => {
if (!response.ok) {
throw new Error('借阅失败,未能与服务器连接');
}
return response.json();
})
.then(data => {
alert('借阅成功!'); // 提示用户成功借阅
loadFavorites(); // 可选:更新收藏页面
loadBorrowHistory(); // 更新借阅历史页面
})
.catch(error => {
console.error('Error:', error);
alert('借阅时发生错误,请稍后再试');
});
}
// 从收藏中删除书籍
function removeFromFavorites(bookId) {
const userId = getUserId();
if (!userId) {
alert('用户信息已失效,请重新登录');
window.location.href = 'login.html';
return;
}
code Copy code
fetch(`http://localhost:8080/api/favorites/remove/${userId}/${bookId}`, {
method: 'DELETE', // 使用 DELETE 方法
headers: {
'Content-Type': 'application/json'
}
})
.then(response => {
if (!response.ok) {
return response.text().then(text => {
throw new Error('删除失败:' + text);
});
}
return response.text(); // 获取成功信息
})
.then(data => {
alert(data); // 提示成功
loadFavorites(); // 重新加载收藏列表
})
.catch(error => {
console.error('Error:', error);
alert('删除收藏时发生错误,请稍后再试');
});
}
</script>
import com.example.librarysystem.dto.FavoriteDTO; // 导入 FavoriteDTO
import com.example.librarysystem.entity.Favorite;
import com.example.librarysystem.service.FavoriteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.Collections;
import java.util.List;
@RestController
@RequestMapping("/api/favorites")
public class FavoriteController {
@Autowired
private FavoriteService favoriteService;
code Copy code
@PostMapping("/add")
public ResponseEntity<?> addFavorite(@RequestBody Favorite favorite) {
try {
// 确保 userId 和 bookId 都不为空
if (favorite.getUserId() == null || favorite.getBookId() == null) {
return new ResponseEntity<>("用户ID和书籍ID不能为空", HttpStatus.BAD_REQUEST);
}
Favorite savedFavorite = favoriteService.addFavorite(favorite);
return new ResponseEntity<>(savedFavorite, HttpStatus.OK);
} catch (Exception e) {
System.err.println("添加收藏时出错: " + e.getMessage());
return new ResponseEntity<>("添加收藏失败: " + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@DeleteMapping("/remove/{userId}/{bookId}")
public ResponseEntity<?> removeFavorite(@PathVariable Long userId, @PathVariable Long bookId) {
try {
favoriteService.removeFavorite(userId, bookId);
return new ResponseEntity<>("成功删除收藏", HttpStatus.OK);
} catch (Exception e) {
System.err.println("删除收藏时出错: " + e.getMessage());
return new ResponseEntity<>("删除收藏失败: " + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@DeleteMapping("/{id}")
public ResponseEntity<?> deleteFavorite(@PathVariable Long id) {
favoriteService.deleteFavorite(id);
return new ResponseEntity<>("Favorite deleted successfully", HttpStatus.OK);
}
// 将返回类型更改为 List<FavoriteDTO>
@GetMapping("/{userId}")
public ResponseEntity<List<FavoriteDTO>> getFavoritesByUserId(@PathVariable Long userId) {
try {
List<FavoriteDTO> favorites = favoriteService.getFavoritesByUserId(userId); // 确保调用对应的方法
return new ResponseEntity<>(favorites, HttpStatus.OK);
} catch (Exception e) {
System.err.println("获取收藏时出错: " + e.getMessage());
return new ResponseEntity<>(Collections.emptyList(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}package com.example.librarysystem.service;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.example.librarysystem.dto.FavoriteDTO;
import com.example.librarysystem.entity.Books;
import com.example.librarysystem.entity.Favorite;
import com.example.librarysystem.mapper.BooksMapper; // 导入 BooksMapper
import com.example.librarysystem.mapper.FavoritesMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
@Service
public class FavoriteService {
@Autowired
private FavoritesMapper favoriteMapper;
code Copy code
@Autowired
private BooksMapper booksMapper; // 添加 BooksMapper
public Favorite addFavorite(Favorite favorite) {
favoriteMapper.insert(favorite); // 使用 BaseMapper 提供的 insert 方法
return favorite;
}
public void removeFavorite(Long userId, Long bookId) {
favoriteMapper.delete(
Wrappers.<Favorite>lambdaQuery().eq(Favorite::getUserId, userId).eq(Favorite::getBookId, bookId)
);
}
public void deleteFavorite(Long id) {
favoriteMapper.deleteById(id);
}
public List<FavoriteDTO> getFavoritesByUserId(Long userId) {
List<Favorite> favorites = favoriteMapper.selectList(
Wrappers.<Favorite>lambdaQuery().eq(Favorite::getUserId, userId)
);
List<FavoriteDTO> favoriteDTOs = new ArrayList<>();
for (Favorite favorite : favorites) {
Books book = booksMapper.selectById(favorite.getBookId()); // 获取书籍信息
FavoriteDTO dto = new FavoriteDTO();
dto.setId(favorite.getId());
dto.setUserId(favorite.getUserId());
dto.setBookId(favorite.getBookId());
dto.setBookTitle(book != null ? book.getTitle() : "未知"); // 书名
dto.setBookAuthor(book != null ? book.getAuthor() : "未知"); // 作者
favoriteDTOs.add(dto);
}
return favoriteDTOs;
}
}
code Copy code
<script>
document.addEventListener("DOMContentLoaded", function () {
updateUsernameDisplay();
});
function logout() {
alert('已退出登录');
localStorage.removeItem('userInfo');
localStorage.removeItem('username');
updateUsernameDisplay();
window.location.href = 'login.html';
}
function updateUsernameDisplay() {
const username = localStorage.getItem('username');
const usernameDisplay = document.getElementById('username-display');
if (username) {
usernameDisplay.textContent = username;
} else {
usernameDisplay.textContent = '未登录';
console.log('在 localStorage 中未找到用户名');
}
}
function showSection(section) {
const sections = document.querySelectorAll('.section');
sections.forEach(s => s.style.display = 'none');
document.getElementById(section + 'Section').style.display = 'block';
if (section === 'favorites') {
loadFavorites();
} else if (section === 'history') {
loadBorrowHistory();
}
}
function searchBooks() {
const keyword = document.getElementById('searchInput').value.trim();
if (keyword === '') {
alert('请输入搜索关键词');
return;
}
// 移除特殊字符
const sanitizedKeyword = keyword.replace(/[%_]/g, '');
fetch('http://localhost:8080/api/books/search', {
method: 'POST',
headers: {
'Content-Type': 'application/json' // 声明使用 JSON 格式
},
body: JSON.stringify({ keyword }) // 将关键词封装成 JSON 发送到后端
})
.then(response => {
if (!response.ok) {
throw new Error('网络响应不正常');
}
return response.json(); // 解析 JSON 数据
})
.then(data => {
displaySearchResults(data); // 将结果显示在页面上
})
.catch(error => console.error('Error:', error)); // 处理异常情况
}
function displaySearchResults(books) {
const searchResults = document.getElementById('searchResults');
searchResults.innerHTML = ''; // 清空之前的结果
code Copy code
// 检查返回的书籍列表是否为空
if (books.length === 0) {
searchResults.innerHTML = '<p>没有找到相关书籍</p>'; // 提示用户未找到书籍
} else {
books.forEach(book => {
const listItem = document.createElement('div');
listItem.className = 'search-result-item';
listItem.innerHTML = `
<div>
<strong>书名:</strong> ${book.title}<br>
<strong>作者:</strong> ${book.author}<br>
<strong>出版年份:</strong> ${book.yearPublished || '未知'}
</div>
<div class="book-actions">
<button onclick="borrowBook(${book.id})">借阅</button>
<button onclick="addToFavorites(${book.id})">添加到收藏</button>
</div>
`;
searchResults.appendChild(listItem); // 将书籍信息添加到显示区域
});
}
}
function getUserId() {
const userInfo = JSON.parse(localStorage.getItem('userInfo'));
return userInfo ? userInfo.id : null;
}
function borrowBook(bookId) {
const userId = getUserId();
if (!userId) {
alert('用户信息已失效,请重新登录');
window.location.href = 'login.html';
return;
}
code Copy code
fetch('http://localhost:8080/api/borrow-records/borrow', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ userId: userId, bookId: bookId }) // 应该在请求体中传递用户和书籍的 ID
})
.then(response => {
if (!response.ok) {
throw new Error('网络响应不正常');
}
return response.json(); // 解析 JSON 数据
})
.then(data => {
alert('您已成功借阅');
loadBorrowHistory();
})
.catch(error => {
console.error('Error:', error);
alert('借阅书籍时发生错误,请稍后再试');
});
}
code Copy code
// 加载借阅历史
function loadBorrowHistory() {
const userId = getUserId();
if (!userId) {
alert('用户信息已失效,请重新登录');
window.location.href = 'login.html';
return;
}
// 更新 API 路径
fetch(`http://localhost:8080/api/borrow-records/user/borrow-history/${userId}`)
.then(response => {
if (!response.ok) {
throw new Error('未找到借阅记录');
}
return response.json();
})
.then(data => {
displayBorrowHistory(data);
})
.catch(error => {
console.error('Error:', error);
alert('加载借阅历史时发生错误,请稍后再试');
});
}
function displayBorrowHistory(borrowRecords) {
const borrowHistory = document.getElementById('borrowHistory');
borrowHistory.innerHTML = '';
code Copy code
if (borrowRecords.length === 0) {
borrowHistory.innerHTML = '<p>没有借阅记录</p>';
} else {
borrowRecords.forEach(record => {
const listItem = document.createElement('li');
const borrowDate = new Date(record.borrow_date || Date.now()); // 若 borrow_date 为 null, 使用当前时间
const formattedDate = borrowDate.toLocaleDateString('zh-CN', {
year: 'numeric',
month: '2-digit',
day: '2-digit'
});
listItem.textContent = `书名: ${record.title || '未知'} - 作者: ${record.author || '未知'} - 借阅日期: ${formattedDate} - 状态: ${record.is_returned ? '已还书' : '未还书'}`;
const returnButton = document.createElement('button');
returnButton.textContent = '还书';
returnButton.onclick = function () {
console.log('Attempting to return book with Record ID:', record.id);
returnBook(record.id, returnButton);
};
if (record.is_returned) {
returnButton.disabled = true;
returnButton.textContent = '已还书';
}
code Copy code
listItem.appendChild(returnButton);
borrowHistory.appendChild(listItem);
});
}
}
function returnBook(borrowRecordId, returnButton) {
const userId = getUserId();
if (!userId || !borrowRecordId) {
alert('无效的用户 ID 或借阅记录 ID');
return;
}
code Copy code
returnButton.disabled = true;
returnButton.textContent = '处理中...';
fetch(`http://localhost:8080/api/borrow-records/return/${borrowRecordId}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
}
})
.then(response => {
return response.text(); // 使用 .text() 解析文本响应
})
.then(data => {
console.log(data)
alert(data); // data 是字符串格式的消息
loadBorrowHistory(); // 重新加载借阅历史
})
.catch(error => {
console.error('Error:', error);
alert('还书时发生错误,请稍后再试');
returnButton.disabled = false;
returnButton.textContent = '还书'; // 恢复按钮状态
});
}
code Copy code
// 添加到收藏
function addToFavorites(bookId) {
const userId = getUserId();
if (!userId) {
alert('用户信息已失效,请重新登录');
window.location.href = 'login.html';
return;
}
fetch('http://localhost:8080/api/favorites/add', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ userId: userId, bookId: bookId }) // 确保这两个值非空
})
.then(response => {
if (!response.ok) {
return response.text().then(text => {
throw new Error('添加收藏时发生错误:' + text);
});
}
return response.json();
})
.then(data => {
alert('已成功添加到收藏!');
loadFavorites(); // 重新加载收藏列表
})
.catch(error => {
console.error('Error:', error);
alert('添加收藏时发生错误,请稍后再试');
});
}
code Copy code
// 加载收藏书籍
function loadFavorites() {
const userId = getUserId();
console.log('加载收藏的用户ID:', userId); // 增加调试信息
if (!userId) {
alert('用户信息已失效,请重新登录');
window.location.href = 'login.html';
return;
}
fetch(`http://localhost:8080/api/favorites/${userId}`)
.then(response => {
if (!response.ok) {
throw new Error('网络响应不正常');
}
return response.json();
})
.then(data => {
displayFavorites(data); // 确保数据结构正确
})
.catch(error => {
console.error('Error:', error);
alert('加载收藏时发生错误,请稍后再试');
});
}
code Copy code
// 显示收藏书籍
function displayFavorites(favoriteBooks) {
const favoritesList = document.getElementById('favoritesList');
favoritesList.innerHTML = '';
if (favoriteBooks.length === 0) {
favoritesList.innerHTML = '<p>没有收藏的书籍</p>';
} else {
favoriteBooks.forEach(favorite => {
const listItem = document.createElement('li');
listItem.innerHTML = `书名: ${favorite.bookTitle} - 作者: ${favorite.bookAuthor}`; // 使用 DTO 中的属性
const borrowButton = document.createElement('button');
borrowButton.textContent = '借阅';
borrowButton.onclick = function () {
borrowFromFavorites(favorite.bookId); // 使用书籍 ID
};
const deleteButton = document.createElement('button');
deleteButton.textContent = '删除收藏';
deleteButton.onclick = function () {
removeFromFavorites(favorite.bookId); // 使用书籍 ID
};
listItem.appendChild(borrowButton);
listItem.appendChild(deleteButton);
favoritesList.appendChild(listItem);
});
}
}
code Copy code
// 从收藏中借阅书籍
function borrowFromFavorites(bookId) {
const userId = getUserId();
if (!userId) {
alert('用户信息已失效,请重新登录');
window.location.href = 'login.html';
return;
}
fetch('http://localhost:8080/api/borrow-records/borrow', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ userId: userId, bookId: bookId }) // 将用户 ID 和书籍 ID 传递
})
.then(response => {
if (!response.ok) {
throw new Error('借阅失败,未能与服务器连接');
}
return response.json();
})
.then(data => {
alert('借阅成功!'); // 提示用户成功借阅
loadFavorites(); // 可选:更新收藏页面
loadBorrowHistory(); // 更新借阅历史页面
})
.catch(error => {
console.error('Error:', error);
alert('借阅时发生错误,请稍后再试');
});
}
// 从收藏中删除书籍
function removeFromFavorites(bookId) {
const userId = getUserId();
if (!userId) {
alert('用户信息已失效,请重新登录');
window.location.href = 'login.html';
return;
}
code Copy code
fetch(`http://localhost:8080/api/favorites/remove/${userId}/${bookId}`, {
method: 'DELETE', // 使用 DELETE 方法
headers: {
'Content-Type': 'application/json'
}
})
.then(response => {
if (!response.ok) {
return response.text().then(text => {
throw new Error('删除失败:' + text);
});
}
return response.text(); // 获取成功信息
})
.then(data => {
alert(data); // 提示成功
loadFavorites(); // 重新加载收藏列表
})
.catch(error => {
console.error('Error:', error);
alert('删除收藏时发生错误,请稍后再试');
});
}
</script>