0

I have recently gotten into html, css, and javascript and am writing a simple website. I need to have an autocomplete textbox. I have a textfile in the same folder as the html and need to read the textfile by newline in order to set the autocomplete sources (i can do that). What i can't do (yet) is get the file text.

I have seen examples with the FileReader() but all of them use the a file object like this.files[0] or from a <input type=file> object event. How can I use a string for the file location ( "search.txt" ) and get the result?

my code:

<body onload="ReadFile()">
<script>
    var data="";

    function ReadFile()
    {
        var fr=new FileReader();
        fr.readAsText("search.txt");
        data=fr.responseText;
    }
</script>
user2155059
  • 151
  • 3
  • 14
  • The filereader is generally for uploaded files, if you need to fetch a file from the server, use serverside code or XMLHttpRequest, and split the text file on newlines. – adeneo Mar 08 '14 at 23:33

1 Answers1

1

you need to use XMLHttpRequest for all browsers and IE7+. However, for IE6 you need to use AciveXObject. You can use get or post request and parse the string after you receive the response from server.

var responseStr; var xmlHttp=new XMLHttpRequest();

xmlhttp.open("GET","search.txt",true); xmlhttp.send();

xmlhtpp.responseText will have the contents of the file. You then further need to parse this.

misthacoder
  • 127
  • 1
  • 1
  • 11
  • when i tried this I got an error saying `XMLHttpRequest cannot load file:///C:/Documents/website/search.txt. Cross origin requests are only supported for HTTP.` btw, the site is not registered with a url, just a file on my computer. So i guess I have to use FileReader – user2155059 Mar 09 '14 at 01:16
  • you might want to use xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { responseStr=xmlhttp.responseText; } } – misthacoder Mar 09 '14 at 01:22
  • if you are using XMLHttpRequest you cant use it to issue request to other domains. the request needs to be made within the same domain. – misthacoder Mar 09 '14 at 01:55
  • so go with the FileReader() ? sorry im really new to this – user2155059 Mar 09 '14 at 02:03