问题
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>
回答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.
来源:https://stackoverflow.com/questions/22276478/javascript-read-from-text-file