Ilya Gazman
Ilya Gazman

Reputation: 32271

open relative text file javascript

How can I read a text file located in relative path of my site using javascript?

This is what I been trying to do and it says access denied:

this.load = function(path){
    if(root == null){
        root = path;
    }

    var client = new XMLHttpRequest();

    client.open('GET', "assets/myTextFile.txt");
    client.onreadystatechange = function() {
        alert(client.responseText);
    };

    client.send();

};

Upvotes: 1

Views: 4415

Answers (2)

Bunlong
Bunlong

Reputation: 662

Please try this code:

var xmlhttp;

if(window.XMLHttpRequest) {
    xmlhttp=new XMLHttpRequest();
}
else {
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}

xmlhttp.onreadystatechange=function() {
    if (xmlhttp.readyState==4 && xmlhttp.status==200) {
        alert(xmlhttp.responseText);
    }
}

xmlhttp.open("GET","assets/myTextFile.txt",true);
xmlhttp.send();

Upvotes: 0

Bunlong
Bunlong

Reputation: 662

If you use jquery:

$.ajax({
  url: "assets/myTextFile.txt",
  success: function(data){
    alert(data);
  }
});

Upvotes: 2

Related Questions