使用JavaScript将文件读入网页

"That which we persist in doing becomes easier, not that the task itself has become easier, but that our ability to perform it has improved."“我们坚持要做的事情变得更加容易,并不是说任务本身变得更加容易,而是我们执行任务的能力得到了提高。” Ralph Waldo Emerson拉尔夫·沃尔多·爱默生

1.简介 (1. Introduction)

One of the wonderful things about the web is that it makes it so easy to look up information.  This is especially true when it comes to finding an answer to a web design problem.  For every problem, it seems, there are hundreds code examples on dozens of sites showing how other developers have solved the problem.  If you look closely you may find there are really only a few ways to solve a certain problems and most of the code snippets rehash the same old solutions.

网络的奇妙之处之一是它使查找信息变得如此容易。 在找到网页设计问题的答案时尤其如此。 对于每个问题,似乎在数十个站点上都有数百个代码示例,这些示例显示了其他开发人员如何解决该问题。 如果仔细观察,您可能会发现实际上只有少数方法可以解决某些问题,并且大多数代码片段都重新表述了相同的旧解决方案。

When looking for code samples on how to read files with JavaScript you will find the same few methods used over and over. Some of those examples are outdated, contain hacks which are no longer needed or are just plain wrong. There are web developers even today who advise that you can not read files with JavaScript. They are wrong! There is a modern, cross browser and elegant solution available in the remote scripting object.

当寻找有关如何使用JavaScript读取文件的代码示例时,您会发现反复使用的几种方法。 其中一些示例已过时,包含不再需要的hack或完全错误。 甚至在

All modern browsers now support remote scripting.  The remote scripting object is also slated for inclusion in the W3C's DOM 3 specification for the next generation of web browsers. Thus it is a firmly established technology.  As long ago as IE 7, you could use the same syntax to create a remote scripting object as is used by Mozilla, Safari, Opera, Chrome, et. al., and which is also used in the DOM 3 specification.

现在,所有现代浏览器都支持远程脚本。 还计划将远程脚本对象包含在下一代Web浏览器的W3C的DOM 3规范中。 因此,这是一项牢固确立的技术。 早在IE 7之前,您就可以使用与Mozilla,Safari,Opera,Chrome等相同的语法来创建远程脚本对象。 ,也用于DOM 3规范中。

While this article may seem trivial to some, it receives the highest number of hits on my web site and has been used by many other people as the answer to the "How do I read files with JavaScript" question here and on numerous other IT Q&A web sites. Given that popularity, I can only assume that we are welcoming a whole new group of web developers to our ranks, and they are looking for solid code examples.

尽管这篇文章对某些人来说似乎微不足道,但它在我的网站上获得的点击次数最高,并且已被许多其他人用作此处和其他众多IT问答中“如何使用JavaScript读取文件”问题的答案。网站。 鉴于这种受欢迎程度,我只能假设我们欢迎一群全新的Web开发人员加入我们的行列,他们正在寻找可靠的代码示例。

Even if you are familiar with the remote scripting object, (also known as the XMLHTTP or just XHR object,) what is unique in this code is that it has been written as a library file and allows file reading via the remote scripting object is as simple as a server side include or the PHP include() function. This code improves error handling, removes some redundant code and adds a couple of options for the developer over previous versions and when compared to similar examples you might find on the web. It also allows multiple "includes" on a given web page, and supports displaying a image to indicate content is being loaded.

即使您熟悉远程脚本对象(也称为XMLHTTP或XHR对象),此代码中的独特之处在于它已被编写为库文件,并允许通过远程脚本对象读取文件。就像服务器端include或PHP include()函数一样简单。 该代码改进了错误处理,删除了一些冗余代码,并为开发人员提供了比以前版本更丰富的选择,并且与您在网上可能发现的类似示例进行了比较。 它还在给定的网页上允许多个“包含”,并支持显示图像以指示正在加载内容。

The example code was written so it degrades nicely in older browsers which do not support the remote scripting object, or for browsers which have disabled JavaScript.

编写示例代码是为了在不支持远程脚本对象的旧版浏览器或禁用JavaScript的浏览器中将其很好地降级。

To see a live example of using remote scripting to read files into a web page please visit the page at the following link. Read File [Live Example].  The live example of the client side include function demonstrates the ability to gracefully fallback for non-remote scripting enabled browsers. The source code for the example is shown on that page but will be included here so we can look a little closer at that code's functionality.

要查看使用远程脚本将文件读入网页的实时示例,请访问以下链接的页面。 读取文件[实时示例] 。 客户端包含功能的实时示例演示了对启用了非远程脚本功能的浏览器进行适当回退的能力。 该示例的源代码显示在该页面上,但将包括在此处,因此我们可以更仔细地了解该代码的功能。

2.使用文件阅读库 (2. Use Of The File Reading Library)

Our JavaScript calls a function which uses the remote scripting object to get the file at the URL passed to the function. The file is simply returned to the page as a string of characters which are loaded into an HTML division. The string returned could be placed in nearly any HTML container, such as in paragraph tags or a span. To call the function is simple, for example;

我们JavaScript调用一个函数,该函数使用远程脚本对象在传递给该函数的URL处获取文件。 该文件只是作为一串字符串返回到页面,这些字符串已加载到HTML分区中。 返回的字符串可以放置在几乎任何HTML容器中,例如段落标签或跨度中。 例如,调用该函数很简单;

<input type="button" value="Include File" onclick="include('http://www.ourdomain.com/path/filename.txt');">

In this example we use the body "onload" event to execute the "include(path/to/file.txt)" command. The include function can be called in many different ways, including from another function, any page event, a link or a button. As written in the example, the content of the remote page is not returned by the "include" function, but are received by a results handling function.

在此示例中,我们使用正文“ onload”事件执行“ include(path / to / file.txt) 可以以许多不同的方式调用include函数,包括从另一个函数,任何页面事件,链接或按钮中调用。如示例中所述,“ include”函数不返回远程页面的内容,但由

As previously mentioned, this code adds additional flexibility by allowing you to specify the results handling function, and optionally a image to indicate the remote contents are being loaded.  So  in the code, we would use:

如前所述,此代码通过允许您指定结果处理功能以及可选的图像来指示要加载的远程内容,从而增加了灵活性。 因此,在代码中,我们将使用:

include(URL[, optionalTargetElementId][, optionalLoadingImageSourcePath]);

3.包含文件代码 (3. The Include File Code)

//<![CDATA[

// Does this browser support try-catch?
var tc = false;
try {
    tc = true;
} catch(f) { }

var xmlHttpError = 'XML HTTP Request: OK';

function getRequestObject() {
    var objRequest;
    if (window.ActiveXObject) {
        if (tc) {
            try {
                objRequest = new ActiveXObject('Msxml2.XMLHTTP');
            }
            catch(e) {
                try {
                    objRequest = new ActiveXObject('Microsoft.XMLHTTP');
                }
                catch(f) { } 
            }
        } else {
            objRequest = new ActiveXObject('Microsoft.XMLHTTP');
        }
    } else if (window.XMLHttpRequest) {
        objRequest = new XMLHttpRequest();
    }
    return objRequest;
}

function include(pUrl,pElementId,pImageSrc) {
    if (arguments.length==3) {
        if (pImageSrc) {
            var el = document.createElement('img');
            // Add the Please Wait Image
            el.setAttribute('src', pImageSrc);
            el.setAttribute('alt', 'Please Wait');
            el.setAttribute('width', 16);
            el.setAttribute('height', 16);
            document.getElementById(pElementId).appendChild(el);
        }
    }        
    var objRequest = getRequestObject();
 
    if (typeof(objRequest)=='object') {
        if (objRequest.readyState>=0) {
            objRequest.onreadystatechange = function() { handleHttpResponse(objRequest, pElementId); };
            objRequest.open('GET', pUrl, true);
            objRequest.send(null);
        }else{
            xmlHttpError = 'XML HTTP Request Object Unavailable';
            document.getElementById(pElementId).innerHTML = xmlHttpError;
            return false;
        } 
    }else{
        xmlHttpError = 'XML HTTP Request Object Not Supported';
        document.getElementById(pElementId).innerHTML = xmlHttpError;
        return false;
    }
}

function handleHttpResponse(pObjRequest, pElementId) {
    if (pObjRequest.readyState==4) {
        if (pObjRequest.status==200) {
            // Remove the Please Wait Image
            for (var idx=0; idx<document.getElementById(pElementId).children.length; idx++) {
                el = document.getElementById(pElementId).children.item(idx);
                if (el.tagName == 'IMAGE') {
                    document.getElementById(pElementId).removeChild(el);
                }    
            }
            document.getElementById(pElementId).innerHTML=pObjRequest.responseText;
            pObjRequest=null;
        }
    }
}

//-->
//]]>

You could cut and paste the code into your page's JavaScript block, however it would be better to save that as "include.js" then add that file to your page with a script tag. Thus:

您可以将代码剪切并粘贴到页面JavaScript块中,但是最好将其保存为“ include.js”,然后使用script标签将该文件添加到页面中。 从而:

<script type="text/javascript" src="include.js"></script>

Now it would be unfair if I did not point out some shortcomings.  Of primary importance would be to note that if you use a language such as PHP that actually has a command or function "include" you may want to rewrite the function to be include_js. That being noted, there should not be a conflict unless you somehow, (and I'm not sure how you could do this,) mixed the JavaScript with your PHP or other server side script.

如果我不指出一些缺点,那将是不公平的。 最重要的是要注意,如果您使用PHP之类的语言实际上具有命令或函数“ include”,则可能要将函数重写为include_js。 需要注意的是,除非您以某种方式(并且我不确定如何做到)将JavaScript与您PHP或其他服务器端脚本混合在一起,否则不应有冲突。

Remote scripting while available in nearly every modern browser, is not available in some browsers such as screen readers for the visually impaired and in some search engine spiders.

远程脚本几乎可以在所有现代浏览器中使用,但在某些浏览器(如视力障碍者的屏幕阅读器)和某些搜索引擎蜘蛛中却无法使用。

The code will also not work if the browser does not have JavaScript enabled. For that reason, the target HTML element can be written to contain an <IFRAME> which loads the page to be included, and we can have a <NOSCRIPT> line in the body to notify the person browsing our page that they need JavaScript enabled to achieve full functionality. Don't forget the paragraph tags inside your <NOSCRIPT> tags or your page will not validate.

如果浏览器未启用JavaScript,则该代码也将不起作用。 因此,可以将目标HTML元素编写为包含<IFRAME>来加载要包含的页面,并且我们在正文中可以包含<NOSCRIPT>行以通知浏览我们的页面的人他们需要启用JavaScript才能实现全部功能。 不要忘记<NOSCRIPT>标记内的段落标记,否则页面将无法通过验证。

Example:

例:

<body>
<noscript><p>This page requires JavaScript to be supported or enabled for complete functionality.</p></noscript>
<p><input type="button" value="Emails.txt" name="b1" onclick="include('http://www.rodsdot.com/javascript/include/emails.txt','theExample','images/loading_icon.gif');">&nbsp;
<input type="button" value="Lincoln.htm" name="b2" onclick="include('http://www.rodsdot.com/javascript/include/lincoln.htm','theExample','images/loading_icon.gif');">&nbsp;
<input type="button" value="Movies.txt" name="b3" onclick="include('http://www.rodsdot.com/javascript/include/movies.txt','theExample','images/loading_icon.gif');">&nbsp;
<input type="button" value="Latin.htm" name="b4" onclick="include('http://www.rodsdot.com/javascript/include/latin.htm','theExample','images/loading_icon.gif');"></p>
<div id="theExample"><iframe name="altFrame" src="http://www.rodsdot.com/javascript/include/latin.htm" scrolling="no" frameborder="0">Your browser does not support inline frames or is currently configured not to display inline frames.</iframe></div>
<script type="text/javascript">
// start by loading latin.htm
include('http://www.rodsdot.com/javascript/include/latin.htm','theExample','images/loading_icon.gif');
</script>
</body>

4。结论 (4. Conclusion)

Is that all?  Just read a file?

这就是全部? 只是读文件?

Well no actually. You can create a select list (drop down box), or a table, and even highlight certain letters or words, see: Create Various Elements From File Data.

好吧,实际上。 您可以创建选择列表(下拉框)或表格,甚至突出显示某些字母或单词,请参阅: 从文件数据创建各种元素

You can even read an external file line-by-line, see: Read A File Line By Line.

您甚至可以逐行读取外部文件,请参阅:逐行读取文件

Or you can sort the file content after reading the file, see: Read And Sort A File Using JavaScript

或者,您可以在读取文件后对文件内容进行排序,请参阅: 使用JavaScript读取和排序文件

翻译自: https://www.experts-exchange.com/articles/3327/Reading-Files-Into-Your-Web-Page-With-JavaScript.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值