从文本文件中提取内容不起作用 JavaScript

Pulling Content From Text File Not Working JavaScript

本文关键字:不起作用 JavaScript 提取 文本 文件      更新时间:2023-09-26

我的HTML文件中的代码:

<!doctype html>
<head>
<title>Notes</title>
<script>
function PullNotes() {
var txtFile = new XMLHttpRequest();
txtFile.open("GET", "notes.txt", true);
txtFile.onreadystatechange = function() {
    if (txtFile.readyState === 4 || txtFile.status == 200) {
        allText = txtFile.responseText;
    }
    document.getElementById('notetext').innerHTML = allText;
}
}
</script>
</head>
<body>
<div id="notetext"><p>Failed.</p></div>
<input type="button" value="Pull Notes" onClick="PullNotes()">
</body>
</html>

当我点击按钮时。什么也没发生。

如果你想知道为什么它说"失败",所以我知道JavaScript没有更新。

谢谢~亿

我相信您需要在分配onreadystatechange属性后调用txtFile.send()。 看看这个。

此外,注释.txt必须位于您正在加载的 html 文件的同级位置。 即 foo.com/index.html -> foo.com/notes.txt

您的代码变为:

function PullNotes() {
    var txtFile = new XMLHttpRequest();
    txtFile.open("GET", "notes.txt", true);
    txtFile.onreadystatechange = function() {
        if (txtFile.readyState === 4 || txtFile.status == 200) {
            allText = txtFile.responseText;
        }
        document.getElementById('notetext').innerHTML = allText;
    }; // end onreadystatchange prop
    // send the request
    txtFile.send();
}