我正在编写我的第一个网站,现在我正在尝试用一些文本文件的内容更改 p 内容,其中包含对我网站内容的详细描述,实际上我已经尝试了很多方法,比如 httprequest( ), FileReader() 和 jquery get,但实际上我没有管理它,因为我在本地运行它并且可能是因为文件位置错误,所以我在女巫中创建了一个新的小代码我尝试了 jquery get,我运行了它在“用于 chrome 的网络服务器”上,但它不起作用。
这是代码:
<!DOCTYPE html>
<html>
<body>
<div><h2 id="demo">Lets change this text</h2></div>
<button type="button" onclick="loadDoc()">Change Content</button>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js">
</script>
<script>
function loadDoc() {
$.get("hello.txt",function(data){
getElementById('demo').innerText= data;
});
}
</script>
</body>
</html>
当我加载它时,显示 p 和按钮,但是当我点击按钮时没有任何反应; .html 和 .txt 文件位于同一文件夹中。 我已经坚持了很多天,请帮忙,不要将其标记为重复。
感谢任何帮助。
最佳答案
你可以试试这个 out
<script>
function loadDoc() {
$.get("hello.txt",function(data){
document.getElementById('demo').innerHTML= data;
});
}
</script>
HTML:
<div><h2 id="demo">Lets schange this text</h2></div>
<button type="button" onclick="loadDoc()">Change Content</button>
<button type="button" onclick="loadDocWithHttp()">Change Content from Http request</button>
使用 AJAX:
function loadDocWithHttp() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("demo").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "hello.txt", true);
xhttp.send();
}
关于javascript - 用文本文件一更改 p 内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38972219/