Jacob Burgess
Jacob Burgess

Reputation: 55

Reading from text url in javascript

I'm trying to make a program in JavaScript, that I already had in Java. I've tried a few different ways reading a url.txt file, and I can't say that I understand any of it. So I would like to avoid Jquery and other non standard options, because I'm trying to learn this language. Here's the html:

<!DOCTYPE html>
<html>
<head>
    <title>Page Title</title>
    <script src="/script.js"></script>
</head>
<body>
    <button onclick="getText()">Try It</button>
    <p id="text"></p>
</body>
</html>

The JavaScript:

function getText() {
    var bool = true;
    var xReq = new XMLHttpRequest();
    xReq.addEventListener("progress", updateProgress);
    xReq.addEventListener("load", transferComplete);
    xReq.addEventListener("error", transferFailed);
    xReq.addEventListener("abort", transferCanceled);
    xReq.open(
      "GET",
      "http://jeff.cis.cabrillo.edu/datasets/santa-cruz-addresses.txt");
    xReq.send();
}
function updateProgress (oEvent) {
    if (oEvent.lengthComputable) {
        var percentComplete = oEvent.loaded / oEvent.total * 100;
    } else {
        // Unable to compute progress information  total size is unknown
    }
}

function transferComplete(evt) {
    document.getElementById("text").innerHTML = "The transfer is complete.";
}

function transferFailed(evt) {
  document.getElementById("text").innerHTML = "An error occurred";
}

function transferCanceled(evt) {
  document.getElementById("text").innerHTML = "canceled by the user.";
}

Eventually I will split the txt file up into lines, and into arrays, but first I need to figure this out , any help would be awesome thanks.

Upvotes: 0

Views: 114

Answers (2)

Charlie
Charlie

Reputation: 23778

The http://jeff.cis.cabrillo.edu should support CORS.

That is, it should tell the browser, through it's response headers, that it has no problem it's services are accessed by this request.

If this information is not found in the response, the browser will simply generate an error.

Upvotes: 1

Pawel
Pawel

Reputation: 46

Because security reasons you cannot make javascript request to external domain. This is possible only if external allow to do that by adding this header: Access-Control-Allow-Origin.

For your issue the best will be just use ajax to read static file from local.

Upvotes: 3

Related Questions