本文介绍了Javascript从文本文件读取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近刚进入html,css和javascript,我正在写一个简单的网站。我需要一个自动填充文本框。我有一个文本文件在与html相同的文件夹,并需要阅读textfile by newline为了设置自动完成源(我可以这样做)。我不能做的(还)是获取文件文本。

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.

我已经看到了 FileReader()的例子,但是他们都使用了一个像this.files这样的文件对象[0]或从< input type = file> 对象事件。 如何使用字符串作为文件位置(search.txt)并获取结果?

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?

我的代码:

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

    function ReadFile()
    {
        var fr=new FileReader();
        fr.readAsText("search.txt");
        data=fr.responseText;
    }
</script>


推荐答案

您需要对所有浏览器和IE7 +使用XMLHttpRequest。但是,对于IE6,您需要使用AciveXObject。您可以使用get或post请求,并在收到服务器的响应后解析字符串。

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();

var responseStr;var xmlHttp=new XMLHttpRequest();

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

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

xmlhtpp.responseText将具有文件的内容。你还需要解析这个。

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

这篇关于Javascript从文本文件读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-26 07:46
查看更多