简体   繁体   中英

How to save my javascript array to a file?

My phonegap/iOS application has a file named data.js which contains an array. The application works with this array and some changes are stored into it.

Now when the user quits my application I want it to save the changes to the data.js file. Is there any way to do this?

UPDATE This is my array (the only thing in data.js ):

    var data = [
        [0, "A", "B", "0", "0"],
        [1, "C", "D", "0", "0"],
        [2, "E", "F", "0", "0"],
        ...
    ];

SOLVED! I used JSON to stringify my array and save it to the localStorage. It only has to work with Mobile Safari, so this is a good solution. Thanks for giving me the hints that made me solve my problem.

If you are using phonegap than for sure you can work with file system. Solution is to encode your array into JSON using serializeArray() method in JQuery.

Once you encode your array you will get JSON string which you have to store in a file using PhoneGap's Filewriter() function. For more detail on that visit this link .

I hope it helped you :-).

JavaScript cannot tamper with the file system directly. You can do one of two things:

  1. Save the changes onto a cookie and read it the next time
  2. Send the changes (via AJAX) to a PHP file which would generate a downloadable file on the server, and serve it to the client.

There are probably more solutions, but these are the most reasonable two I can think of.

Phonegap (at http://phonegap.com/tools/ ) is suggesting Lawnchair: http://westcoastlogic.com/lawnchair/

so you'd read that file into data.js instead of storing the data literally there

You could also save your array (or better yet its members) using localStorage, a key/value storage that stores your data locally, even when the user quits your app. Check out the guide in the Safari Developer Library .

use Lawnchair to save the array as a JSON object. The JSON object will be there in the memory till you clear the data for the application.
If you want to save it permanently to a file on the local filesystem then i guess you can write a phonegap plugin to sent the data across to the native code of plugin which will create/open a file and save it.

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