JavaScript + JSON -


i got json format dataset in file data.json:

{     "timestamp": "wed apr 02 2014, 19:03:19",      "test": [            441.02,         null,         null,         460.99,         485.91,         501.0,         null,         null,         null,         null     ],      "test1": [         437.0,         null,         null,         464.989,         488.52,         499.996,         null,         null,         null,         null     ] } 

and need push values array[] in javascript like:

var test = [441.02, null, null, 460.99, 485.91, 501.0, null, null, null, null] 

var test1 = [437.0, null, null, 464.989, 488.52, 499.996, null, null, null, null] 

can point me in right direction? i'm javascript newbie.

first, must load json , parse using json.parse():

var xmlhttp = new xmlhttprequest(),     me = this,     test = null,     test1 = null;  // note: change data.json json file xmlhttp.open('get', 'data.json', true); xmlhttp.onreadystatechange = function() {     // if got request     if (xmlhttp.readystate === 4 && xmlhttp.status === 200) {         // parse json data.json         var obj = json.parse(xmlhttp.responsetext);         me.test = obj.test;         me.test1 = obj.test1;          // manipulation here. can call other functions here.         dootherstuff();     } };  // send request data xmlhttp.send(null);  function dootherstuff() {     console.log(me.test); // work because called inside function } 

references:

get json array pure js , parse json in javascript?.

note: must all data manipulation inside of if statement inside onreadystatechange function because request asynchronous. onreadystatechange function fired when ready state changed. if statement true if data request. if try access data outside if statement, not work. here's little diagram showing why:

   request made using xmlhttp.send(null) |--code after xmlhttp.send(null) executed |  request complete |  request onreadystatechange function called (readystate = 4 && status = 200) v v v (code continues execute) 

notice how code after xmlhttp.send(null) executed before request complete? that's why must data manipulation inside onreadystatechange function.

edit: make array globally accessible, declare in global scope, set inside onreadystatechange function. call functions need test inside onreadystatechange function. (see above edits code.)


Comments

Popular posts from this blog

PHPMotion implementation - URL based videos (Hosted on separate location) -

javascript - Using Windows Media Player as video fallback for video tag -

c# - Unity IoC Lifetime per HttpRequest for UserStore -