要使用JSON数据填充表单,你需要遵循以下步骤:
{
"name": "John Doe",
"email": "john.doe@example.com",
"phone": "123-456-7890"
}
querySelector
)来获取它们。例如:const nameInput = document.getElementById('name');
const emailInput = document.getElementById('email');
const phoneInput = document.getElementById('phone');
const jsonString = '{"name":"John Doe","email":"john.doe@example.com","phone":"123-456-7890"}';
const jsonData = JSON.parse(jsonString);
for (const key in jsonData) {
if (jsonData.hasOwnProperty(key)) {
const input = document.getElementById(key);
if (input) {
input.value = jsonData[key];
}
}
}
将以上代码整合在一起,可以创建一个函数来填充表单:
function fillFormWithJson(jsonString) {
const jsonData = JSON.parse(jsonString);
for (const key in jsonData) {
if (jsonData.hasOwnProperty(key)) {
const input = document.getElementById(key);
if (input) {
input.value = jsonData[key];
}
}
}
}
const jsonString = '{"name":"John Doe","email":"john.doe@example.com","phone":"123-456-7890"}';
fillFormWithJson(jsonString);
现在,当你调用fillFormWithJson
函数并传入JSON字符串时,表单将被填充。请确保在HTML中为每个输入元素设置了正确的ID。
没有搜到相关的文章