Javascript 如何使用jquery将数据更新到外部json文件中?
我有Javascript 如何使用jquery将数据更新到外部json文件中?,javascript,jquery,json,Javascript,Jquery,Json,我有data.json文件,但无法将数据保存到data.json文件中。我有产品阵列 { "products": [ { "first": 0, "last": "Ocean Blue Shirt", "des": "Ocean blue cotton shirt with a narrow collar and buttons down the" }, { "id": 1,
data.json
文件,但无法将数据保存到data.json
文件中。我有产品阵列
{
"products": [
{
"first": 0,
"last": "Ocean Blue Shirt",
"des": "Ocean blue cotton shirt with a narrow collar and buttons down the"
},
{
"id": 1,
"name": "orange",
"description": "Ocean blue cotton shirt with a narrow collar and buttons down"
}
]
}
下面是我的jquery代码。我正在使用jquery函数$.getJSON()
当我尝试将数据保存到外部json文件名
data.json
中时,我的文件未更新。是否尝试保存持久数据?记住,jQuery是客户端的,所以您将把这些数据保存在浏览站点的个人计算机上
您可能正在寻找某种API,您可以(从客户端)向其发送数据,以便将其保存在服务器上…或将此数据保存在cookie/会话存储/本地存储中的客户端
我不确定在客户端保存数据有多容易。。例如你写的是哪条路?如果用户在手机上浏览怎么办?如果他们在Ubuntu或Windows上呢?所有这些路径都会有所不同
说到这里,我编写了一个小示例,使用jQuery
自动下载JSON数据。。这可能有助于你实现自己的目标
HTML:
$(document).ready(function(){
$.getJSON("data.json", function(data){
data.products.push({
first:'Mike',
last:'jule',
des:'1920-1932'
});
JSON.stringify(data);
});
});
<h3 id="title">The JSON data below will be downloaded in <span id="count"></span> seconds</h3>
<pre id="to-download">
{
"some": "jsonData",
"for": {
"you": "to",
"down": "load"
}
}
</pre>
function download(filename, text) {
const e = document.createElement("a");
e.setAttribute(
"href",
"data:text/plain;charset=utf-8," + encodeURIComponent(text)
);
e.setAttribute("download", filename);
e.style.display = "none";
document.body.appendChild(e);
e.click();
document.body.removeChild(e);
}
function timer(seconds, callback) {
var n = seconds;
$("#count").html(n);
function countDown() {
n--;
if (n > 0) { setTimeout(countDown, 1000); }
$("#count").html(n);
if (n === 0) { callback(); }
}
countDown();
}
timer(10, () => {
const html = $("#to-download").html();
const text = JSON.stringify(JSON.parse(html));
const filename = "data.json";
download(filename, text);
$("#title").html("Done!");
});