首先声明,我知道我要做的不是最好的方式。
现在开始进入正题:
我需要通过javascript来更新JSON文件中的数据。以下是JSON文件的当前状态:
{
"nextid" : 3,
"ingredients" : [
{
"id": 1,
"name": "onion",
"kilojoules": 180,
"quantity": 1,
"measurement": "whole",
"nutrition": [
{"value": "Fat Total", "quantity": 110},
{"value": "Saturated Fat", "quantity": 46},
{"value": "Sodium", "quantity": 4},
{"value": "Carbohydrates Total", "quantity": 10000},
{"value": "Sugar", "quantity": 5000},
{"value": "Fibre", "quantity": 2000},
{"value": "Proten", "quantity": 1000}
]},
{
"id" : 2,
"name": "carrot",
"kilojoules": 56,
"quantity": 1,
"measurement": "whole",
"nutrition": [
{"value": "Fat Total", "quantity": 66},
{"value": "Saturated Fat", "quantity": 11},
{"value": "Sodium", "quantity": 26},
{"value": "Carbohydrates Total", "quantity": 3000},
{"value": "Sugar", "quantity": 2000},
{"value": "Fibre", "quantity": 1000},
{"value": "Proten", "quantity": 279}
]}
]
}
现在假设我想要编辑胡萝卜对象。我已经在我的html页面上构建了一个更新后的胡萝卜对象,并将其作为一个对象放置在javascript中。那么,我需要做些什么来更新源json文件呢?
就像我之前所说的,我知道这并不理想。我应该使用数据库来存储和操作数据,但现在我已经铺好了床,无论这让你们感到多么难受,我都必须让它工作起来。
研究告诉我,我需要在服务器端使用PHP或ASP来收集javascript传递给它的参数,但我不知道该从哪里开始。
我正在使用Visual Studio 2012进行开发,项目的参数禁止我使用插件。NuGet代码库是可以用的,但不能使用插件。基于这个条件,我认为我不能使用PHP。我的想法正确吗?
注意:是的,这是一个任务,但修改json文件超出了要求的范围。能够动态处理json数据就足够了,但我真的很想能够把一些数据写回去。
提前致谢。
编辑:可能也应该分享一下这个打开json文件的javascript代码。打开的结果存储在名为ingJson的脚本全局变量中。
function downloadIngredients() {
$(document).ready(function () {
$.getJSON("/data/ingredientsInfo.js", function (result) {
try
{
ingJson = result;
ingredients = result.ingredients;
ingredients.sort(orderByNameAscending);
buildListBox(ingredients);
}
catch (err) {
alert(err.message);
}
});
});
}
JSON.stringify(obj)
- 然后将其POST回服务器。无论你使用哪种服务器端技术,因为它只需要读取POST并将其写入JSON文件即可。 - MarcoL