在这段代码中,我想保存交易并在重新加载页面时取回交易,以便记录永远保留在那里。但它似乎不是这样工作的。我不想做任何服务器端工作。我希望所有代码都在同一页上。任何想帮助我的人。必须为我修复完整的代码,因为我对此很陌生。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Money Transfer System</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="profile" id="user1">
<h2>User 1</h2>
<p>Balance: $<span class="balance">100</span></p>
<input type="number" class="amount" placeholder="Enter amount">
<input type="text" class="receiver" placeholder="Receiver username">
<button onclick="sendAmount(1)">Send Money</button>
<h3>Transaction Records</h3>
<ul class="transactionRecords"></ul>
</div>
<div class="profile" id="user2">
<h2>User 2</h2>
<p>Balance: $<span class="balance">150</span></p>
<input type="number" class="amount" placeholder="Enter amount">
<input type="text" class="receiver" placeholder="Receiver username">
<button onclick="sendAmount(2)">Send Money</button>
<h3>Transaction Records</h3>
<ul class="transactionRecords"></ul>
</div>
<script>
function sendAmount(sender) {
let parentProfile = document.getElementById('user' + sender);
let amount = parseFloat(parentProfile.getElementsByClassName('amount')[0].value);
let receiver = parentProfile.getElementsByClassName('receiver')[0].value;
let balanceElement = parentProfile.getElementsByClassName('balance')[0];
let balance = parseFloat(balanceElement.textContent);
if (receiver !== "user" + sender) { // Prevent sending to oneself
if (amount > 0 && amount <= balance) {
// Validate the receiver's username
if (receiver === "user1" || receiver === "user2") {
// Deduct the amount from sender's balance
balance -= amount;
balanceElement.textContent = balance;
// Update sent records for the sender with date and time
let sentRecords = parentProfile.getElementsByClassName('transactionRecords')[0];
let sentRecord = document.createElement('li');
let currentDate = new Date().toLocaleString(); // Get the current date and time
sentRecord.textContent = `Sent $${amount} to ${receiver} - ${currentDate}`;
sentRecords.appendChild(sentRecord);
// Update received records for the receiver with date and time
let receiverProfile = document.getElementById('user' + (receiver === "user1" ? 1 : 2));
let receiverBalanceElement = receiverProfile.getElementsByClassName('balance')[0];
let receiverBalance = parseFloat(receiverBalanceElement.textContent);
receiverBalance += amount;
receiverBalanceElement.textContent = receiverBalance;
let receivedRecords = receiverProfile.getElementsByClassName('transactionRecords')[0];
let receivedRecord = document.createElement('li');
receivedRecord.textContent = `Received $${amount} from User ${sender} - ${currentDate}`;
receivedRecords.appendChild(receivedRecord);
} else {
alert("Invalid receiver username. Please enter 'user1' or 'user2'.");
}
} else {
alert("Invalid amount or insufficient balance");
}
} else {
alert("You cannot send money to yourself.");
}
// After updating the transaction records, save the transaction to transaction.txt
saveTransactionToTxt(sentRecord.textContent); // save the transaction details to file
}
function retrieveTransactions() {
fetch('transaction.txt')
.then(response => response.text())
.then(data => {
// Parse the data and populate transaction records
// Example:
// let transactionRecords = data.split('\n');
// transactionRecords.forEach(record => {
// // Populate transaction records in the respective user profiles
// });
})
}
function saveTransactionToTxt(transactionDetails) {
fetch('saveTransaction.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ transaction: transactionDetails })
})
.then(response => {
if (response.ok) {
// Transaction details saved successfully
} else {
// Handle error
}
})
.catch(error => {
// Handle error
});
}
// Call retrieveTransactions when the page loads to populate transaction records
window.onload = retrieveTransactions;
</script>
</body>
</html>
<script>
function sendAmount(sender) {
// After updating the transaction records, save the transaction to localStorage
saveTransactionToLocalStorage(sender, sentRecord.textContent);
saveTransactionToLocalStorage(receiver === "user1" ? 2 : 1, receivedRecord.textContent);
}
function saveTransactionToLocalStorage(user, transactionDetails) {
let transactions = localStorage.getItem('transactions_user' + user);
transactions = transactions ? JSON.parse(transactions) : [];
transactions.push(transactionDetails);
localStorage.setItem('transactions_user' + user, JSON.stringify(transactions));
}
function loadTransactions() {
for (let user = 1; user <= 2; user++) {
let transactions = localStorage.getItem('transactions_user' + user);
if (transactions) {
transactions = JSON.parse(transactions);
let transactionList = document.getElementById('user' + user).getElementsByClassName('transactionRecords')[0];
transactions.forEach(transaction => {
let listItem = document.createElement('li');
listItem.textContent = transaction;
transactionList.appendChild(listItem);
});
}
}
}
// Call loadTransactions when the page loads to populate transaction records
window.onload = loadTransactions;
</script>
saveTransactionToLocalStorage
函数将每笔交易保存在localStorage中。它为每个用户保留一系列交易。
页面加载时调用 loadTransactions
函数。它从 localStorage 检索存储的交易并填充每个用户的交易记录。