简体   繁体   中英

Javascript reading .txt file and displaying in HTML

I'm trying to have JavaScript on my HTML page read from a .txt file (status.txt) in the same directory and display the contents in two different font colors based on the information in the .txt file. I currently have it displaying the text on the page just fine, but I wanted to make it a bit more noticeable. Here is my current code to display the text with the basic #ccc hex.

<script type="text/javascript">
  loadXMLDoc();
</script>
<script type="text/javascript">
  function loadXMLDoc() {
    var xmlhttp;
    if (window.XMLHttpRequest) {
      xmlhttp = new XMLHttpRequest();
    }
    xmlhttp.onreadystatechange = function() {
      if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        document.getElementById("status").innerHTML = xmlhttp.responseText;
      }
    }
    xmlhttp.open("GET", "status.txt", true);
    xmlhttp.send();
  }
</script>

<h3 id="status" style="padding-right: 7px; padding-left: 7px; margin-top: 2px; font-size: 11px; color: #cccccc">
  Status
</h3>

The text file contents are overwritten every time a .vbs file is ran. It will either say:

6/11/2016 8:58:30 AM Script Started

or

6/11/2016 9:31:12 AM Script Stopped

The only thing that changes is the timestamp. I would like the text to display as red when it says "(timestamp) Script Stopped" and green when it says "timestamp) Script Started". If anyone could help, that'd be great!

You can use simple RegEx to add proper classes to your text.

document.getElementById("status").innerHTML = xmlhttp.responseText
    .replace(/(\b\d.+?Started)/ig,'<span class="start">$1</span>')
    .replace(/(\b\d.+?Stopped)/ig,'<span class="stop">$1</span>');
    //\b -start of word, \d - any digit 0 to 9, . - any character
    // +? - one ore more, not greedy 
var color = xmlhttp.responseText.indexOf('Started') !== -1 ? 'green' : 'red';
document.getElementById("status").innerHTML = '<span style="color: ' + color + '">' + xmlhttp.responseText + '</span>';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM