Jquery Posting Json To Local File
Solution 1:
Here's my solution to my own problem, based on comments:
Ok, so it isn't possible to post to a local file as mentioned by some of the comments, but by using localStorage and JSON.stringify
and JSON.parse
as suggested, the data can still be stored locally like so:
functiongetServerData()
{
$.getJSON("js/servers.json").success(function (data)
{
// Add JSON to localStorage under serverDatalocalStorage.setItem("serverData", JSON.stringify(data));
// Do stuff
}
}
When retrieving, I found that you have to first retrieve the data, then parse it back into a JSON object like so:
functionretrieveData()
{
var temp = localStrage.getItem("serverData");
var jsonData = JSON.parse(temp);
// Do stuff with JSON data
}
Also, I learned that localStorage data for a Phonegap application is persistent as long as the app is installed on the device, even if it is closed or stopped manually by the user.
I'm also checking to see if the data already exists via this if/else statement:
if (typeof (Storage) != "undefined")
{
if (!localStorage.getItem("serverData"))
{
alert("setting server data");
// Ajax JSON to get server informationgetServerData();
}
else
{
retrieveData();
}
}
else
{
alert("localStorage unavailable!");
}
This statement will usually return true for both ifs unless the app is being opened for the first time after install. I would not recommend using localStorage for any JSON data coming from a non-local web service if that data is likely to be changed by something other than the inputs from this application, as this is only a proof of concept for an application I am prototyping.
Post a Comment for "Jquery Posting Json To Local File"