简体   繁体   中英

Load array from txt an load into html the data

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

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.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM