0

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?

3 Answers 3

3

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/>');
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you Rich for answering with a suggestion :)
This is best if one decides to do further processing to lines, like wrapping them in other html elements for style or doing processing. However if simply just replacing line breaks with html br element tags, the global replace that saganbyte suggested should be more efficient.
I will be using this to watch log files for updates in real time. I think your solution will work best. Thanks again!
1

.replace only replaces the first instance of \n

document.getElementById("myDiv").innerHTML=xmlhttp.responseText.replace("\n", "<br />");

1 Comment

There are already a multitude of posts on stackoverflow on javascript string replacement, I thought it would have been helpful to diagnose your error.
0

To replace \r, \n or \r\n globally:

var str = xmlhttp.responseText;
var replacedStr = str.replace(/\r\n|\r|\n/g,"<br />");
document.getElementById("myDiv").innerHTML = replacedStr;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.