JavaScript - Json Issue
Hi
I have some JSON strings and I want to embed it into my website. The problem is that I don't know how to parse JSON string data into html code. After a long search it seem that there is just a few references and manuals about JSON. Could someone explain to me how to use this function and also with as many examples as possible for understanding, how to put it into html page. Thank You Similar TutorialsI have been able to parse a JSON feed before but forwhatever reason this time around I am having a hell of a time getting it working. Here is where I am at right now. So far the script dosn't output anything. Code: <table width="100%" border="0" cellspacing="0" cellpadding="10"> <script> xhttp=new XMLHttpRequest(); xhttp.open("GET","http://biz104.inmotionhosting.com/~cox7co5/api/get_category_posts/?id=5",false); xhttp.send(""); json_data=xhttp.responseText; var parsed_data = eval('('+json_data+')'); var slug="stuff" for (i=0;i<parsed_data.count;i++) { document.write("<tr><td><a href=\"#\" class=\"showlist\">"+parsed_data.posts[i].title+"</a></td><tr>"); } </script> </table> I have a very large json file, and inside of that json file is an array. I would like to use JavaScript to take that json as an argument, parse through the json and only take certain elements from it and put it into a new json file, below is an example of what I mean: Code: { "contextType": "Account", "preferences": null, "custodianCode": null, "data": [{ "id": "0", "account": "11111111", "field2": true, "field3": false, "field4": "BROK", "field5": "Broker", "field6": "1", "field7": "Cash" },{ "id": "1", "account": "222222222", "field2": true, "field3": false, "field4": "BROK", "field5": "Broker", "field6": "1", "field7": "Cash" }] } And I want to pull from that and get something like this as a new json Code: { "newArray": [{ "id": "0", "account": "11111111", "field2": true, "field3": false, "field4": "BROK", "field6": "1" },{ "id": "0", "account": "222222222", "field2": true, "field3": false, "field4": "BROK", "field6": "1" }] } Also the file is local to my computer and can be outputted locally as well, I am trying to use node.js and JavaScript this is what I have so far Code: var json = require('./simple.json'); var keeperFields = ["id", "account", "field2", "field3", "field4", "field6"]; var newJSON = {newArray: [] }; var i; var fields; for (i = 0; i < keeperFields.length; i++) { for (fields in json) { if (json.hasOwnProperty(keeperFields[i])) { newJSON.newArray.push(keeperFields[i]); } } } console.log(newJSON); This is just a small example the real json file is huge with thousands of lines. Any help or suggestions are appreciated! This current solution is giving me a console log of { newArray: []} instead of the expected result above Hello all, I thought I'd share something that I don't see talked about much on the forums. I've been doing a bunch of AJAX development at work. We're really strapped for processing speed on our client (we build the machines our clients use) and therefore we've needed to find ways of speeding everything up. One of the things we decided on within the first week of our current project was to completely scrap XML in favor of JSON for sending data back and forth. JSON is JavaScript Object notation. Many of you have already seen it, it looks like this: Code: {'prop1' : 'someValue', 'prop9' : 5}; That defines an object with 2 properties, prop1 and prop9, with the respective values "someValue" and 5. Compare that to XML: Code: <obj> <prop1 value="someValue" type="String" /> <prop2 value="5" type="Integer" /> </obj> That's a bit more bloated, maybe not too noticeable, but the example is a small one. If you take large amounts of data, and multiple objects, XML can get incredibly bloated, and bloat on the wire slows down your app. That's the first reason we switched. The second reason we switched is that we save time on the processing. We all know what it's like to get at XML data. Import the document, get the node, get the value, get the next node, get the value. And building XML documents can take just as long: Create document, create root node, create node, create attribute node, set value, append child, repeat... All that processing for something so simple. JSON on the other hand is a subset of javascript, so check this out. Code: var data = "{'prop1':'someValue', 'prop2':5}"; var obj = eval("(" + data + ")"); alert(obj.prop1); // *** Alerts 'someValue' *** The string fits right into JavaScript in one function call. Granted, eval can be expensive, but if you test this out yourself, it's far cheaper than building and deconstructing XML in the JavaScript engine. There are 2 simple JSON parsing libraries that we use in development: JSON.php and json.js; these provide the necessary functions to serialize any PHP object into JSON, and serialize any JavaScript object into JSON. You can get them at the links below. We are also following the specification for JSON-RPC, defined in the last link below. We found this to be incredibly fast when compared to XML, and we haven't regretted it yet. Granted, we're not doing full blown web services where the the javascript modifies itself based on the service's self-definition, complete with namespaces and function signatures, but we transfer a lot of data quickly and efficiently to provide our users with the best experience possible. I recommend examining this further if you do AJAX development. Hopefully this helped somebody. http://json.org/ http://mike.teczno.com/json.html http://json-rpc.org/ And now for the "VS" part of this post: Anyone with experience in using both XML and JSON that wants to argue the mertis of either technique? I support JSON for almost all AJAX applications currently. I haven't found a good reason to use XML, and the negatives for using XML (bloat and processing speed) have currently knocked it completely from my "viable options" list. Anyone care to discuss? hello i am using a json file to import some content into a div like this: Code: $.getJSON('json/main_profile.json', function(data) { $('#info_title').html( '<h1>' + "General Information " + '</h1>' ); }); but the problem appears when i try to replace the json file with a url, like this: Code: $.getJSON("http://interfaces-server.insource.local/users/145198", function(data) { $('#info_title').html( '<h1>' + "General Information " + '</h1>' ); }); why works with the file but not with the link?? thanks I've been using the JSON.stringify method to convert my JSON object to a string to pass via AJAX but I've read now that it is not supported in most browsers. What then should I use?
hey guys im trying to create this script which will show array depending on what option has been selected on the select box...but the only thing being returned is "unidentified"....can anyone explain where i am going wrong please...thank you Code: <!DOCTYPE html> <html> <head> <script type="text/javascript" src="/ajax/jquery/libary/jquery.js"></script> </head> <body> <?php $game_type = array(); $division = array(); if ($_POST['game'] == 1) { $game_type[] = array('value' => '1', 'text' => 'TDM' ); $game_type[] = array('value' => '1', 'text' => 'CTF' ); $division[] = array('value' => '1', 'text' => 'Divison 1' ); } elseif ($_POST['game'] == 2) { $game_type[] = array('value' => '1', 'text' => 'CTF' ); $division[] = array('value' => '1', 'text' => 'Divison 2' ); } json_encode($game_type); json_encode($division); ?> <form> <script> $(document).ready(function(){ $("select#game").change(function(){ var post_string = "game=" + $(this).val(); $.ajax({ type: 'POST', data: post_string, cache: false, dataType: 'json', url: 'json.php', timeout: '2000', error: function() { alert("Error has occured"); }, success: function(data) { $.each(data, function(i, j){ var row = "<option value=\"" + j.value + "\">" + j.text + "</option>"; $(row).appendTo("select#sub_category"); }); } }); }); }); //$('#game_type').html('<input type=\"checkbox\" value=\"test\" /> TDM'); //$('#division').html('<input type=\"checkbox\" value=\"test\" /> Division 1'); </script> <select name="game" id="game"> <option value=""></option> <option value="1">Counter Strike</option> <option value="2">COD</option> </select> <div id="game_type"> </div> <div id="division"> </div> <select name="sub_category" id="sub_category"> <option value="">-- Select First Value --</option> </select> </form> </body> </html> I'm trying to get a return of Code: [ ["red","green","blue"] ,["blue","red","green"] ] from a text file that contains Code: red,green,blue blue,red,green Using the following function Quote: Originally Posted by Old Pedant Code: function WRITE_FILE_AS_JSON(file) { fso = Server.CreateObject("Scripting.FileSystemObject"); myPath=Server.MapPath("timecards/" + file); if(!fso.FileExists(myPath))return; myfile = fso.OpenTextFile( myPath, read); var lines = myfile.readAll().split("\n"); Response.Write("[\n"); for ( var i = 0; i < lines.length; ++i ) { Response.Write(' ' + (i >0 ? ',' : '' ) + '["' + lines(i).replace(/\,/g,'","') + '"]\n'); } Response.Write("]\n"); myfile.Close(); Response.End(); } The darn thing keeps returning Quote: 500 (Internal Server) Error as a result of the line Response.Write(' ' + (i >0 ? ',' : '' ) + '["' + lines(i).replace(/\,/g,'","') + '"]\n'); And I don't know how to fix that line... I am making a dynamic google map and need to pass in a JS Object that has latitude, longitude, address, name, and a link. The JS Object will be getting those values from a DB and may have up to 15 recordsets. I need to know how to separate that out into it's entities to include in the Map API regardless of how many recordsets there are.
All, Say I have the following code: Code: <!DOCTYPE html> <html> <head> <style>img{ height: 100px; float: left; }</style> <script src="http://code.jquery.com/jquery-1.7rc2.js"></script> </head> <body> <div id="images"> </div> <script> $.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?", { tags: "cat", tagmode: "any", format: "json" }, function(data) { $.each(data.items, function(i,item){ $("<img/>").attr("src", item.media.m).appendTo("#images"); if ( i == 3 ) return false; }); });</script> </body> </html> This came from the jQuery website. What I would like to do is change the link to something like this: https://graph.facebook.com/me/friend...ss_token=12345 The data that comes back is something like: Code: { "data": [ { "review_comment": "Here is a comment", "id": "12" }, { "review_comment": "Testing With more", "id": "34" }, { "review_comment": "Third comment", "id": "643" }, { "review_comment": "More Comments", "id": "120" }, { "review_comment": "Testing", "id": "3455" } ] } What I would like to do is basically read all of the review_comment tags and basically rotate these to display them on the webpage. So have "Here is a comment" be displayed for like 10 seconds and then fade out and have "Testing with More" fade in and be displayed for another 10 seconds etc. What is the best way to do this? I'm not sure how to change my JSON code above to acheive this. Would I need to basically put the comments in a div and then use jQuery to fade in the divs in and out? Any help you could provide would be greatly appreciated!! I am currently working on a project that requires pretty large bits of jQuery (atleast for me) and once I get this function working I can solve more required functions but I have problems getting this to work. Basically what im trying to do is, when a link is clicked (within a certain div) it reads out the class of that link and searches within XML or JSON for the title and then finds the description within that record. I hope someone is able to point to the right direction, Thanks in advance, Mehk. i have a variable $page that is storing code similar to this PHP Code: onloadRegister(function (){Quickling.init("329319;0", 10, {"page_cache":1,"quickling_init_page":false,"flush_cache_in_transition":1,"flush_cache_in_page_write":0});}); onloadRegister(function (){JSCC.init({"j4d235b8b8399023097431421":function(){return new AsyncLayout();}}, false);}); onloadRegister(function (){JSCC.init({"j4d235b8b8399023097431422":function(){return new SearchDataSource({"maxResults":8,"queryData":{"viewer":100000503667042},"queryEndpoint":"\/ajax\/typeahead\/search.php","bootstrapData":{"viewer":100000503667042,"token":"1294162702-5","lfe":1},"bootstrapEndpoint":"\/ajax\/typeahead\/first_degree.php"});},"j4d235b8b8399023097431423":function(){return new Typeahead(JSCC.get('j4d235b8b8399023097431422'), {node: $("u282757_1"), ctor: "SearchTypeaheadView", options: {"autoSelect":true,"renderer":"search"}}, {node: $("q"), ctor: "SearchTypeaheadCore", options: {"keepFocused":false,"resetOnSelect":true}}, $("u282757_2"))}}, false);}); onloadRegister(function (){window.__UIControllerRegistry["c4d235b8b883d27291189921"] = new UIPagelet("c4d235b8b883d27291189921", "\/pagelet\/profile\/tux_toolbar.php", {"profile_id":100000503667042,"sk":"wall"}, {});; ;}); onloadRegister(function (){ft.enableFeedTracking();}); onloadRegister(function (){JSCC.get('j4d235b8b8399023097431421').init($("contentArea"), $('rightCol'), $('headerArea'), $('toolbarContainer'));}); onloadRegister(function (){window.loading_page_chrome = true;}); PHP Code: $page = curl_exec($curl_handle); $d = json_decode($page); $profileid = $d['profile_id']; htmlOut("kevins profile id = ".$profileid); function htmlOut($var){ echo "<hr /><b>".$var."</b><hr />"; } This is what i have but its not isolating the profile id does anybody know how i can do this please the id im looking for is 100000503667042 thanks for any help provided. In IE, the output is as expected, all four values print to the page. In every other rendering engine, the title data does not, neither of them. This is really quite simple I can't understand what the issue could be. No errors showing in any browser. function JSONpop() { var JSONtest = {"items": [ { "title": "sample 1", "author": "author 1" }, { "title": "sample 2", "author": "author 2" } ]}; var testClass = document.getElementsByTagName('div')[0].getAttribute('class'); if(testClass=="news-story") { document.getElementsByTagName('div')[0].childNodes[0].innerHTML = JSONtest.items[0].title; document.getElementsByTagName('div')[0].childNodes[1].innerHTML = "By: "+JSONtest.items[0].author; document.getElementsByTagName('div')[0].childNodes[2].innerHTML = JSONtest.items[1].title; document.getElementsByTagName('div')[0].childNodes[3].innerHTML = "By: "+JSONtest.items[1].author; } } hihi i am doing a project regarding ajax how am i going to call the title because normally if you call start year is like var detail = eval.... then for loop it inside should be var start year="" startyear += ...[i].startyear something like this but how am i going to call the title inside the note? Code: { "infos": { "info": [ { "startYear": "1900", "endYear": "1930", "timeZoneDesc": "daweerrewereopreproewropewredfkfdufssfsfsfsfrerewrBlahhhhh..", "timeZoneID": "1", "note": { "notes": [ { "id": "1", "title": "Mmm" }, { "id": "2", "title": "Wmm" }, { "id": "3", "title": "Smm" } ] }, "links": [ { "id": "1", "title": "Red House", "url": "http://infopedia.nl.sg/articles/SIP_611_2004-12-24.html" }, { "id": "2", "title": "Joo Chiat", "url": "http://www.the-inncrowd.com/joochiat.htm" }, { "id": "3", "title": "Bake", "url": "https://thelongnwindingroad.wordpress.com/tag/red-house-bakery" } ] } I'm quite new to javascript programming, I basically want to parse a JSON string from an external URL. http://cashtrackr.com/piwik/index.ph...9d8d472cc9974a This is the json string URL and I just want to output the contents of "nb_visits" for example. I would also like to know the terms for a JSON string "?" : ? thanks for your time the "count" field/value on this JSON example for the MarkerClusterer app http://google-maps-utility-library-v.../src/data.json http://gmaps-utility-library.googlec.../examples.html i am trying to produce a similar JSON result and i cant figure out where their "count" variable is calculated at 10785236 for... but the following does not work Code: var data = { "count": 2, "photos": [{"photo_id": 1, "photo_title": "testing", "photo_url": "http://www.site.com/photo/522084", "photo_file_url": "http://www.site.com/avatars/test.jpg", "longitude": -97.6765157, "latitude": 31.1482230, "width": 500, "height": 350, "upload_date": "7 September 2010", "owner_id": 1, "owner_name": "b747fp", "owner_url": "http://www.site.com/user/1"} , {"photo_id": 2, "photo_title": "testing", "photo_url": "http://www.site.com/photo/522084", "photo_file_url": "http://www.site.com/avatars/test.jpg", "longitude": -118.4104684, "latitude": 34.1030032, "width": 500, "height": 350, "upload_date": "7 September 2010", "owner_id": 4, "owner_name": "test", "owner_url": "http://www.site.com/user/4"} ] } hi there i need your help. i would like to build a small poll. client should receive the data from server (a JSON file). client will load the data. It'll send the selection to the server, after the user has acted. The poll should look like this. **** are you a linux user? Yes No **** Yes and No with radio buttons. So the end result should look like this..If i open a website, the page will be dynamically created and it'll load the data ("are you a linux user?") from the server. The selection will be sent to the server where this saves the selection. Hope someone could help me out with this? hi, in my page he http://www.mypubspace.com/dashtest/order.html I would like this working Cross Domain and output in JSON? Can anyone please help me? thanks code: Code: <html> <body> <script language="javascript" type="text/javascript"> <!-- //Browser Support Code function ajaxFunction(){ var townRequest; // The variable that makes Ajax possible! try{ // Opera 8.0+, Firefox, Safari townRequest = new XMLHttpRequest(); } catch (e){ // Internet Explorer Browsers try{ townRequest = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try{ townRequest = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e){ // Something went wrong alert("Your browser broke!"); return false; } } } // Create a function that will receive data sent from the server townRequest.onreadystatechange = function(){ if(townRequest.readyState == 4){ var ajaxDisplay = document.getElementById('ajaxDiv'); ajaxDisplay.innerHTML = townRequest.responseText; } } var name = document.getElementById('name').value; var county = document.getElementById('county').value; var town = document.getElementById('town').value; var queryString = "?name=" + name + "&county=" + county + "&town=" + town; //Add the following line townRequest.open("GET", "http://www.mypubspace.com/dashtest/townpubs.php" + queryString, true); townRequest.send(null); } function countyFunction(){ var countyRequest; // The variable that makes Ajax possible! try{ // Opera 8.0+, Firefox, Safari countyRequest = new XMLHttpRequest(); } catch (e){ // Internet Explorer Browsers try{ countyRequest = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try{ countyRequest = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e){ // Something went wrong alert("Your browser broke!"); return false; } } } // Create a function that will receive data sent from the server countyRequest.onreadystatechange = function(){ if(countyRequest.readyState == 4){ var ajaxDisplay = document.getElementById('ajaxDiv'); ajaxDisplay.innerHTML = countyRequest.responseText; } } var name = document.getElementById('name').value; var county = document.getElementById('county').value; var town = document.getElementById('town').value; var queryString = "?name=" + name + "&county=" + county + "&town=" + town; //Add the following line countyRequest.open("GET", "http://www.mypubspace.com/dashtest/countypubs.php" + queryString, true); countyRequest.send(null); } function townlistFunction(){ var ajaxRequest; // The variable that makes Ajax possible! try{ // Opera 8.0+, Firefox, Safari ajaxRequest = new XMLHttpRequest(); } catch (e){ // Internet Explorer Browsers try{ ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try{ ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e){ // Something went wrong alert("Your browser broke!"); return false; } } } // Create a function that will receive data sent from the server ajaxRequest.onreadystatechange = function(){ if(ajaxRequest.readyState == 4){ var ajaxDisplay = document.getElementById('ajaxTownlist'); var county = document.getElementById('county').value; var town = document.getElementById('town').value; ajaxDisplay.innerHTML = ajaxRequest.responseText; } } ajaxRequest.open("GET", "http://www.mypubspace.com/dashtest/town-select.php", true); ajaxRequest.send(null); } function countylistFunction(){ var ajaxRequest; // The variable that makes Ajax possible! try{ // Opera 8.0+, Firefox, Safari ajaxRequest = new XMLHttpRequest(); } catch (e){ // Internet Explorer Browsers try{ ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try{ ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e){ // Something went wrong alert("Your browser broke!"); return false; } } } // Create a function that will receive data sent from the server ajaxRequest.onreadystatechange = function(){ if(ajaxRequest.readyState == 4){ var ajaxDisplay = document.getElementById('ajaxCountylist'); ajaxDisplay.innerHTML = ajaxRequest.responseText; } } ajaxRequest.open("GET", "http://www.mypubspace.com/dashtest/county-select.php", true); ajaxRequest.send(null); } function MM_jumpMenu(targ,selObj,restore){ //v3.0 eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'"); if (restore) selObj.selectedIndex=0; } //--> </script> <a href="#" onClick="townlistFunction();">show towns list</a> <a href="#" onClick="countylistFunction();">show counties list</a> <form name='myForm'> <div id="ajaxTownlist"></div> <div id="ajaxCountylist"></div> <input type='hidden' id='name' /> <input type='hidden' id='county' /> <input type='hidden' id='town' /> </form> <div id='ajaxDiv'></div> </body> </html> a simple NO YOU CAN'T or a BUY A TEXTBOOK & READ IT will probably answer my query.. what i want to do is to analyse a load of share bulletin boards, from a webpage on my home pc. i'd hoped to do it by putting the bb page in an iframe and parsing the iframe's innerHTML. but this is barred by javascript. i'm a bit cheesed off having found that out only after doing the hard work of writing the parsing-code.. (i had pasted a sample bulletin board source code into the iframe, so it was all local..) but i read something about JSON.. which might outflank the security. i'd like to know: can i get an example of how this might be done? how much of a learning curve is JSON. can i fix it up on this machine? thanks for any help.. When I call my controller function template it should select the template name from database and find the matching image.png Currently when I call the function from view via json it only displays no_image.png even though both links work. I have echoed and tested. For my controller it is CodeIgniter Based. How can I get my json script code work. It is calling URL fine. If image name does not match the $this->input->get('template') name should display no image. Codeigniter Controller Function Code: public function template() { $this->load->library('response'); if ($this->input->server('HTTPS')) { $server = HTTPS_SERVER; } else { $server = HTTP_SERVER; } if (is_file(FCPATH . '/image/' . 'templates/' . basename($this->input->get('template')) . '.png')) { $this->response->setOutput($server . 'image/templates/' . basename($this->input->get('template')) . '.png'); } else { $this->response->setOutput($server . 'image/no_image.jpg'); } } View Code: <div class="form-group"> <label class="col-sm-2 control-label" for="input-template"><?php echo $entry_template; ?></label> <div class="col-sm-10"> <select name="config_template" id="input-template" class="form-control"> <?php foreach ($templates as $template) { ?> <?php if ($template == $config_template) { ?> <option value="<?php echo $template; ?>" selected="selected"><?php echo $template; ?></option> <?php } else { ?> <option value="<?php echo $template; ?>"><?php echo $template; ?></option> <?php } ?> <?php } ?> </select> <br /> <img src="" alt="" id="template" class="img-thumbnail" /> </div> </div> </div><!-- / End Tab Website --> <div class="tab-pane" id="tab-local"> </div> <div class="tab-pane" id="tab-option">Option</div> <div class="tab-pane" id="tab-server">Server</div> </div> </form> </div> </div> </div> </div> <script type="text/javascript"><!-- $('select[name=\'config_template\']').on('change', function() { $.ajax({ url: 'http://localhost/codeigniter/admin/?c=website/&m=template&template=' + encodeURIComponent(this.value), dataType: 'html', beforeSend: function() { $('select[name=\'country_id\']').after(' <i class="fa fa-circle-o-notch fa-spin"></i>'); }, complete: function() { $('.fa-spin').remove(); }, success: function(html) { $('.fa-spin').remove(); $('#template').attr('src', html); }, error: function(xhr, ajaxOptions, thrownError) { alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText); } }); }); $('select[name=\'config_template\']').trigger('change'); //--></script> Hey, I'm wondering how do I go about saving an array object in JSON. I got some help in saving game.money, as you see below in the code. That is something I couldn't figured out on my own even after searching for ages. Now I'm wonder how do I save an array such as game.buildings[0]. It's the same as game.money except it's an array. All inputs are greatly appreciated! Code: function save() { var save = { game: { money: game.money } }; localStorage.setItem("save", JSON.stringify(save)); }; function load() { var GameTwo = JSON.parse(localStorage.getItem("save")); if (typeof GameTwo.game.money !== "undefined") game.money = GameTwo.game.money; document.getElementById("money").innerHTML = game.money; }; Reply With Quote 01-19-2015, 06:13 AM #2 Old Pedant View Profile View Forum Posts Supreme Master coder! Join Date Feb 2009 Posts 28,311 Thanks 82 Thanked 4,754 Times in 4,716 Posts Nothing magic about arrays. Use the same code: Code: function saveArray( usingName, anArrayToSave ) { localStorage.setItem( usingName, JSON.stringify(anArrayToSave)); }; function loadArray( nameToLoad ) { return JSON.parse( localStorage.getItem( nameToLoad ) ); } Heck, here's a complete demo: Code: <!DOCTYPE html> <html> <body> <div id="before"></div> <hr/> <div id="after"></div> <hr/> <script type="text/javascript"> function saveArray( usingName, anArrayToSave ) { localStorage.setItem( usingName, JSON.stringify(anArrayToSave)); }; function loadArray( nameToLoad ) { return JSON.parse( localStorage.getItem( nameToLoad ) ); } var foo = loadArray("zamboni"); var div = document.getElementById("before"); if ( foo == null ) { div.innerHTML = "First time"; foo = [ "apples", "bananas", "canteloupe", "dates", "eggplant", "falafel" ]; } else { div.innerHTML = foo.join(","); } foo.sort( function() { return Math.random() < 0.5 ? -1 : 1; } ); div = document.getElementById("after"); div.innerHTML = foo.join(","); saveArray( "zamboni", foo ); </script> </body> </html> |