简体   繁体   中英

How to push data to external JSON file (Using jQuery)?

I want to push an data to array in external local JSON file using jQuery.

So any ideas?

I have tried this:

$.getJSON('test.json', function(data) {
data.push('Something');
});

And it wont be pushed into local JSON file

Is not possible to write files using Javascript (can cause security problems through xss, csrf ..)

No, JavaScript doesn't have access to writing files as this would be a huge security risk to say the least. If you wanted to get/store information server- side, though, you can certainly make an Ajax call to a PHP/ASP/Python/etc. script that can then get/store the data in the server. If you meant store data on the client machine, this is impossible with JavaScript alone. I suspect Flash/Java may be able to, but I am not sure.

If you are only trying to store a small amount of information for an unreliable period of time regarding a specific user, I think you want cookies. I am not sure from your question what you are trying to accomplish, though.

Read/write to file using jQuery

You can do this in JavaScript with node.js (or a multitude of other languages/platforms ) but not with a browser & jQuery.

Here's how to read and write a json file in node.js

On the other hand, users could upload a JSON file to your server, where you modify the structure and send them a modified JSON file back as a download.

You cannot access the files in a local client's machine. May be for development setup you can do it. But before you need to restart the browser with file-access flag set.

You can see my answer here that describes the opening browser setup with the flag set.

Then, you can use the following code to read the data.

var data = [];
var url = "/Users/Vignesh/Desktop/test.json";
var req = new XMLHttpRequest();
req.open("GET",url,true);
req.onreadystatechange=function(){
    if(req.readyState === 4)
    {
        data = JSON.parse(req.responseText);
    }
};
req.send();

To write into the file you may look into this . (Not sure it is working or not)

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