[英]Reading a txt file from Server, writing it to website
这是我的问题。
1)我想创建一个txt文件(或者可能是一个html文件)来保存用户点击单词时要写入的信息段。 这是我正在进行的游戏的一部分。
如果你去www.w3schools.com并去他们的“试试”编辑,他们有......
<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc()
{
var xmlhttp = XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
p = document.createElement("p");
p.innerHTML=xmlhttp.responseText;
document.getElementById("story").appendChild(p);
}
}
xmlhttp.open("GET","ajax_info.txt",true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="story"><h2>Let AJAX <i onclick=loadXMLDoc()>change</i> this text</h2></div>
</body>
</html>
这正是我希望我的程序要做的事情(当然不是实际的话)但是我正在使用外部.js表运行html。 我应该把我的ajax存放在别的地方吗? 或者,我的.txt文件应该看起来不同于其中的一堆单词吗? 我完全糊涂了。
有趣的部分将是一旦这实际开始工作,我将不得不在txt文件中实现带斜体的“onclick”事件。
如果有更好的方法,那么appendChild(p.innerHTML(“lfjhdfh”))和AJAX请尽快告诉我。 我总共有11个星期的时间来为学校项目LOL工作。
试试这个,它只是将文本附加到body
元素的HTML:
function getFileFromServer(url, doneCallback) {
var xhr;
xhr = new XMLHttpRequest();
xhr.onreadystatechange = handleStateChange();
xhr.open("GET", url, true);
xhr.send();
function handleStateChange() {
if (xhr.readyState === 4) {
doneCallback(xhr.status == 200 ? xhr.responseText : null);
}
}
}
function ajax() {
getFileFromServer("Test.txt", function (text) {
if (text === null) {
// An error occurred
} else {
document.body.innerHTML += test;
}
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.