【发布时间】:2017-11-20 22:27:00
【问题描述】:
我有以下代码在表格中显示有关人员的信息,当单击标记为“学习”的按钮时,该信息将存储在键/值类型数组中,然后将其拼接到指定的 JSON 对象中。
所有这些都可以正常工作,但我想更改保存 JSON 对象本身的文件,这意味着我需要处理服务器端代码。如何将此插入到我的 JSON 对象中并实际更改它存储的文本文件(这样如果我打开它,新信息就会在那里)?
我的代码如下-->
index.html
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="list.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<title></title>
</head>
<body>
<table>
<tr>
<td>
<table>
<tr><td>Name</td><td class="name">Jenkins</td></tr>
<tr><td>Job</td><td class="job">Accountant</td></tr>
<tr><td>Size</td><td class="size">Small</td></tr>
</table>
</td>
<td class="description">average joe.</td>
<td>
<button class="learn">Learn</button>
</td>
</tr>
</table>
<script type="text/javascript">
$(".learn").click(function(){
// look at jsonData in list.js and append this element to the items list in the
// first element, at the first index without removing any content
jsonData[0].items.splice(0, 0, {
name: $(this).closest("table").find(".name").text(),
job: $(this).closest("table").find(".job").text(),
size: $(this).closest("table").find(".size").text(),
description: $(this).closest("td").siblings(".description").text()
});
// to show that it is properly appending the new information to the existing JSON object
console.log(jsonData);
});
</script>
</body>
</html>
list.js -->
var jsonData = [
{
name: "Friends",
items: [
{
name: "Steve",
job: "pro bowler",
size: "tall",
description: "Steve's my man!"
},
{
name: "Jessica",
job: "HR",
size: "average",
description: "a dear friend"
}
]
},
{
name: "Co-Workers",
items: [
{
name: "Martin",
job: "my boss",
size: "tall",
description: "I don't like him"
},
{
name: "Susan",
job: "Intern",
size: "average",
description: "It's not like I have a crush on her or anything..."
}
]
}
]
同样,在控制台中可以看到 jsonData 中添加了“jenkins”的信息;但是,文本文件本身保持不变,我希望它反映这一添加。谢谢。
【问题讨论】:
标签: javascript php json ajax splice