user2078343
user2078343

Reputation: 21

How to load data from external file in array

Having tried a whole day loading data from a file using jquery, I did not succeed. In a javascript I defined an array of values as a global variable, it will be used in a following function. The variable looks like this:

var Yvalue01 = [7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6]

However, I would like to load these values from a text file on the server that has the following content:

7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6

How can I do this in javascript (no php)?

Upvotes: 2

Views: 1343

Answers (2)

ShaneQful
ShaneQful

Reputation: 2236

You can use an XHR request to retrieve the file and parse it e.g.

function reqListener () {
    var Yvalue01 = this.responseText.split(",");//Split the response by commas
    Yvalue01 = Yvalue0.map(function (el) { return parseFloat(el);});//Parse the values to make them numbers
    //Do stuff with your array
}

var oReq = new XMLHttpRequest();
oReq.onload = reqListener;
oReq.open("get", "yourFile.txt", true);
oReq.send();

See the MDN docs for more details: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest

Jquery and other javascript libraries(e.g. dojo) have nicer apis for doing this e.g.

Upvotes: 1

Vivek
Vivek

Reputation: 315

You have to use AJAX to get the file and then parse it.

For example the following code gets a file called data.txt that has the following numbers and loads it into an array called values.

The contents inside data.txt:

7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6

Here's the code: (requires jQuery because it makes it easier)

function getFile(location)
{
    var result;
    $.ajax(
    {
        type: 'GET',
        async: false,
        url:  location,
        success: function(data) {
            result = data;
        },
        fail: function() {
            result = null;
        }
    });
    return result;
}

var values = getFile("data.txt").split(",");

The location variable is a string of the relative file path of the file on the server.

Upvotes: 0

Related Questions