Reputation: 706
function loadTextDoc(url, cfunc) {
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = cfunc;
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
function myFunction() {
var values = [];
var i;
loadTextDoc("../menu.txt", function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
menus.innerHTML = xmlhttp.responseText;
values = xmlhttp.responseText;
for(i in values) {
alert(values[i]);
}
}
});
}
Hi so I have these 2 functions for retreieving information from a txt file which contains some data like this: ["bug", "jungle", "tom", "farm", "panda", "frog"]. What ai want to do is put every array information ie. bug, jungle etc intro a anchor in html. but the above 2 functions consider my array as a whole, each letter or even [ or " is shown as an array elemen. For example arr[0] is equal to [, arr[1] = ", arr[2] = b, arr[3] = u an so on. Can anyone explain what i'm doing wrong.
Thanks a lot
Upvotes: 1
Views: 57
Reputation: 2114
Your data is a string so you need to parse it before using it as you want:
arr = JSON.parse(arr);
Now you can use "arr" as you want :)
EDIT: You can use this data in another function using global variables or parameters.
Examples:
var values = [];
function myFunction() {
var i;
loadTextDoc("../menu.txt", function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
menus.innerHTML = xmlhttp.responseText;
values = JSON.parse(xmlhttp.responseText);
for(i in values) {
alert(values[i]);
}
}
});
}
function another() {
// Now you can access "values" from here
}
Or:
function myFunction() {
var values = [];
var i;
loadTextDoc("../menu.txt", function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
menus.innerHTML = xmlhttp.responseText;
values = JSON.parse(xmlhttp.responseText);
for(i in values) {
alert(values[i]);
}
another(values);
}
});
}
function another(data) {
// Now you can access "values" from here
// using "data" parameter
}
But in last example "values" will desapear after myFunction execution.
Upvotes: 1