本文介绍了如何通过Javascript/AJAX逐行显示文本文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从服务器读取文本文件,并在我的网页上的div中显示.这是我的AJAX/Javascript:

I am trying to read a text file from the server and display in a div on my web page. Here is my AJAX/Javascript:

    <body onload="loadXMLDoc()">
    <script>
        function loadXMLDoc()
        {
            var xmlhttp;
            if (window.XMLHttpRequest)
            {// code for IE7+, Firefox, Chrome, Opera, Safari
                xmlhttp=new XMLHttpRequest();
            }
            else
            {// code for IE6, IE5
                xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
            }
            xmlhttp.onreadystatechange=function()
            {
                if (xmlhttp.readyState==4 && xmlhttp.status==200)
                {
                    document.getElementById("myDiv").innerHTML=xmlhttp.responseText.replace("\n", "<br />");
                }
            }
            xmlhttp.open("GET","ajax_info_test.txt?t=" + Math.random(),true);
            xmlhttp.send();
            setInterval (loadXMLDoc, 1000);
        }
    </script>
    <div id="myDiv"></div>
</body>

它仅在文本文件的第一行中显示第一行.我该如何针对每一行单独执行此操作?

It only displays the first line in the text file on its own line. How can I do this for each line on its own?

推荐答案

由于Brad M似乎未完全回答,您的问题是您仅替换了一行.请使用以下命令删除所有\ n并使用br标签加入.

As Brad M seems to incompletely answer, your problem is you are only replacing one line. Use the following to remove all \n and join with br tag instead.

xmlhttp.responseText.split('\n').join('<br/>');

这篇关于如何通过Javascript/AJAX逐行显示文本文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-02 15:51