简体   繁体   中英

How to update data into external json file using jquery?

I have the data.json file but I am not able to save data into the data.json file. I have products array

{ 
"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"

       }
      ]
}

The below is my jquery code.I am using jquery function $.getJSON()

$(document).ready(function(){

    $.getJSON("data.json", function(data){

            data.products.push({
                first:'Mike',
                last:'jule',
                des:'1920-1932'
            });

            JSON.stringify(data);
    });
});

My file is not updating when I tried to save data into external json file name data.json .

Are you trying to save persistent data? Remember, jQuery is client side - so you will be saving this data on the persons computer that browses your site.

What you may be looking for is some sort of an API that you can send data to (from the client), so that you can save it on your server...or to save this data client side in a cookie/session storage/local storage..?

I am not sure how easy it would be to save data client side.. For example; what path do you write? What if the user browses on a phone? What about if they are on Ubuntu, or Windows? All of those paths would be different..

With that being said, I wrote a little example that automatically downloads JSON data using jQuery .. This may be able to help you achieve what you are trying to do..

[Live CodePen demo to show you how this works..]

HTML:

<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>

jQuery:

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!");
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM