我创建了三个页面:createUser.js、UpdateUser.js、readUser.js 和index.html,它们只是收集员工的用户详细信息并存储它们。我使用了创建文件,它工作并创建了一个 JSON 数据。我使用了
readUser
文件,它可以读取用途。我什至手动添加了更多用户详细信息,以便可以读取 JSON 文件,但是 updateUser
会覆盖我的 bin 内的 JSON 数据并添加新的用户详细信息。
我已经阅读了 jsonbin 的文档,但仍然找不到我做错了什么。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>User Details Form</title>
<style>
/* Add your CSS styles here */
</style>
</head>
<body>
<h1>User Details Form</h1>
<form id="userForm">
<label for="firstName">First Name:</label>
<input type="text" id="firstName" name="firstName" required><br>
<label for="lastName">Last Name:</label>
<input type="text" id="lastName" name="lastName" required><br>
<label for="age">Age:</label>
<input type="number" id="age" name="age" required><br>
<label for="yearOfEmployment">Year of Employment:</label>
<input type="number" id="yearOfEmployment" name="yearOfEmployment" required><br>
<label for="hobbies">Hobbies:</label><br>
<input type="checkbox" id="reading" name="hobbies" value="Reading">
<label for="reading">Reading</label><br>
<input type="checkbox" id="cooking" name="hobbies" value="Cooking">
<label for="cooking">Cooking</label><br>
<input type="checkbox" id="hiking" name="hobbies" value="Hiking">
<label for="hiking">Hiking</label><br><br>
<!-- Address section -->
<label for="street">Street:</label>
<input type="text" id="street" name="street" required><br>
<label for="city">City:</label>
<input type="text" id="city" name="city" required><br>
<label for="country">Country:</label>
<input type="text" id="country" name="country" required><br>
<button type="submit">Submit</button>
</form>
<!--<script src="jsonbin.js"></script>-->
<script src="jsonbin2.js"></script>
</body>
</html>
document.addEventListener('DOMContentLoaded', function() {
const form = document.getElementById('userForm');
form.addEventListener('submit', async function(event) {
event.preventDefault(); // Prevent default form submission
// Get form values
const firstName = document.getElementById('firstName').value;
const lastName = document.getElementById('lastName').value;
const age = document.getElementById('age').value;
const yearOfEmployment = document.getElementById('yearOfEmployment').value;
const hobbies = getHobbies();
const street = document.getElementById('street').value;
const city = document.getElementById('city').value;
const country = document.getElementById('country').value;
// Create user object
const newUser = {
firstName,
lastName,
age,
yearOfEmployment,
hobbies,
address: {
street,
city,
country
}
};
// Call function to update user details
await updateUserDetails(newUser);
});
// Function to get selected hobbies
function getHobbies() {
const checkboxes = document.getElementsByName('hobbies');
const selectedHobbies = [];
checkboxes.forEach(function(checkbox) {
if (checkbox.checked) {
selectedHobbies.push(checkbox.value);
}
});
return selectedHobbies;
}
// Function to update user details
async function updateUserDetails(newUser) {
const binId = 'xxaaxx'; // Replace with your bin ID
const apiUrl = `https://api.jsonbin.io/v3/b/${binId}`;
try {
// Fetch existing user data
const response = await fetch(apiUrl, {
method: 'GET',
headers: {
'X-Master-Key': 'xxxxxxxx'
}
});
if (response.ok) {
const userData = await response.json();
let updatedUser;
if (userData.record) {
const existingUser = userData.record.data;
// Merge existing user data with new user data
updatedUser = {
...existingUser,
...newUser
};
} else {
updatedUser = newUser;
}
// Update user details
await fetch(apiUrl, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
'X-Master-Key': 'xxxxxxx'
},
body: JSON.stringify({ data: updatedUser })
});
alert('User details updated successfully now!');
form.reset(); // Clear the form after updating details
} else {
throw new Error('Failed to fetch existing user data');
}
} catch (error) {
console.error(error);
alert('Failed to update user details. Please try again later.');
}
}
});
问题似乎与您用于更新 JSONBin 中的用户数据的方法有关。您使用的 PUT 方法是将 JSONBin 中的现有数据替换为新用户,而不是将现有数据与新数据合并。
要解决此问题,您可以在推送更新之前手动将现有数据与新数据合并。以下是您可以执行此操作的方法:
异步函数 updateUserDetails(newUser) { const binId = 'xxaaxx'; // 替换为你的 bin ID const apiUrl =
https://api.jsonbin.io/v3/b/${binId}
;
try {
// Fetch existing user data
const response = await fetch(apiUrl, {
method: 'GET',
headers: {
'X-Master-Key': 'xxxxxxxx'
}
});
if (response.ok) {
const userData = await response.json();
let updatedUser;
if (userData.record) {
const existingUser = userData.record.data;
// Merge existing user data with new user data
updatedUser = {
...existingUser,
...newUser
};
} else {
updatedUser = newUser;
}
// Update user details
await fetch(apiUrl, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
'X-Master-Key': 'xxxxxxx'
},
body: JSON.stringify({ data: updatedUser })
});
alert('User details updated successfully now!');
form.reset(); // Clear the form after updating details
} else {
throw new Error('Failed to fetch existing user data');
}
} catch (error) {
console.error(error);
alert('Failed to update user details. Please try again later.');
}
}