2

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)?

1

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

3 Comments

The OP didn't specify the use of JQuery
True, but I think it makes it easier to make AJAX requests.
I completely agree with you but the OP may be using another library or may not want to use any at all.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.