I am an absolute JavaScript newbie, however I am working on a private Project. In a nutshell I will be reading a few flat files (.csv/.txt format) and passing the values to HighCharts.
I have a handle on nearly everything (I think).
The only bit I can't get is reading the files into an array, then picking the bits out I need. I can use a script to pass the files straight into Highcharts, but it's not flexible enough for what I need.
Anyway for the below Livedata.txt contains
1370576580,Acidity,pH,8.20,ORP,mV,366.99,ReefTemp,DegC,25.1,RoomTemp,DegC,21.7,HeaterTemp,DegC,25.1
(EPOCH, then groups of 3 data points (measure, unit, value) for 5 probes)
My (the snippet of my) script is:
var $livedata = new Array();
var currentph;
$.get('livedata.txt', function(data){
livedata = data.split(',');
});
currentph = $livedata[3];
document.write("<b>currentph is </b>=>"+currentph+"<br>");
like this the var currentph = undefined
If I move the document.write statement into the $.get (is this a function?) it does contain the value 8.20
Furthermore if I declare currentph as 8.20 the rest of my script accepts this value fine.
Any help/suggestions are much appreciated.
I will be declaring 16 variables, 1 for each value in the array (just for the sake of reading the script later).
Cheers
Because the $.get
is asyn. When you call currentph = $livedata[3];
right after that, the response does not arrive yet. That's the reason why it works when you move the document.write
statement into the $.get
's callback function. Also check your typo, you're missing $
before livedata
. If you need to do syn call, you can try $.ajax
with async:false
$.ajax(
{
url:'livedata.txt',
async:false,
success: function(data){
$livedata = data.split(',');
}
}
);
$
to your variable livedata
. $livedata
would be an empty array; b) If 'livedata.txt' is loaded, but does not have at least 4 comma separated values, the $livedata[3]
would be undefined. You may want to re-write your code with something like this:
var $livedata = []; // array literal notation
$.get('livedata.txt', function(data){
$livedata = data.split(',');
});
// in case array does not have an index 3, set value to 'not found'
var currentph = $livedata[3] || 'not found';
document.write("<b>currentph is </b>=>"+currentph+"<br>");
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.