【问题标题】:Pulling Content From Text File Not Working JavaScript从文本文件中提取内容不起作用 JavaScript
【发布时间】:2013-09-08 22:36:18
【问题描述】:

我的 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 没有更新。

谢谢, ~BN

【问题讨论】:

  • notes.txt 是在您的文件系统上还是在 http 服务器上?如果您通过foo.com/index.html 访问此html 页面,则notes.txt 需要为@foo.com/notes.txt。你还需要send()我认为的请求。
  • 把它放在你的 if 块中:document.getElementById('notetext').innerHTML = allText;
  • @SB。服务器。我在本地和服务器上都试过了。

标签: javascript html button onclick xmlhttprequest


【解决方案1】:

我相信您需要在分配onreadystatechange 属性后调用txtFile.send()。检查this

此外,notes.txt 必须位于您正在加载的 html 文件的同级位置。 IE。 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();
}

【讨论】:

  • 我应该把它放在哪里? .onreadystatechange 之后的那一行?
  • 谢谢!!! txtFile.send();修复!但是我的文本文件是多行的,整个内容都是一行。
  • @Brandon - 这是因为您将其作为 html 插入,而 HTML 会忽略换行符。您可以将所有 \n 替换为 &lt;br/&gt; 作为 hack - 请参阅此答案。 stackoverflow.com/questions/784539/…
  • 或者你可以把它放在&lt;pre&gt; 块中。
  • 你能把每两行放在一个单独的div里吗?
猜你喜欢
  • 1970-01-01
  • 2020-01-16
  • 1970-01-01
  • 2013-02-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多