2017-01-28 72 views
3

如何显示文本content.txt以及其中要显示为常规html的标签?从文本文件中显示文本格式为html?

+0

使用'XMLHttpRequest'获取文件的内容,并使用'.innerHTML'将其插入容器中。 –

+0

这个问题是问题和答案样式。我已经alleyy回答了它 –

回答

1

首先,创建文件content.txt,然后在其中写入要显示的html源文件。例如:
content.txt

Yep, this is the content.txt! 
Some html? 
<code>This is the code tag</code> 
<button class="btn btn-primary" onclick="hideAjax()">Hide content.txt</button> 
<h1>It works!</h1> 

HTML

<div id="ajaxResponse"> 
    content.txt isn't displayed 
</div> 
    <button type="button" onclick="loadAjax()" class="btn btn-primary">Show text from content.txt</button> 

JS/AJAX

function loadAjax() { 
    var xhttp = new XMLHttpRequest(); 
    xhttp.onreadystatechange = function() { 
    if (this.readyState == 4 && this.status == 200) { 
     document.getElementById("ajaxResponse").innerHTML = 
     this.responseText; 
    } 
    }; 
    xhttp.open("GET", "content.txt", true); 
    xhttp.send(); 
} 

注:我已经foun d这在testingc.ga,所以一定要看看他们的版本。

+0

在xhttp.open中为** content.txt **可以插入完整路径,如:https://domain.tld/directory/file.txt,但要注意Cross Origin(CORS Error) ! –