0
我有以下代码显示表中某个人的信息,并且当单击标记为“learn”的按钮时,该信息将存储在键/值类型数组中然后被拼接到指定的JSON对象中。通过AJAX或PHP将JavaScript数据写入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”的信息;但是,文本文件本身保持不变,我希望它能反映这一点。谢谢。
这似乎用添加的元素替换文件中的所有内容。 – laroy
@laroy我已经更新了上面的代码(在'json_decode()'中忘了'true'以将对象作为数组处理) – Sebastian
当我读取json数据以填充我网站上的另一个表格时,我将其称为jsonData(如上面代码所示)。假设你的例子中的“data.json”意思是list.js,它将替换代码中说“var jsonData = [”有没有办法让我克服这个替换,以便我可以继续引用这样的文件? – laroy