我正在尝试做一个基本的AJAX教程,将文件hello.txt中的数据读取到我的网页中。hello.txt和我当前的html网页在同一个目录中。有人知道我做错了什么吗?当我加载页面时,没有任何反应。
<!DOCTYPE html>
<head><title>Ajax Test</title>
<script type="text/javascript">
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", "hello.txt", true);
xmlHttp.addEventListener("load", ajaxCallback, false);
xmlHttp.send(null);
function ajaxCallback(event){
alert( "Your file contains the text: " + event.target.responseText );
}
</script>
</head>
<body>
</body>
</html>
发布于 2013-11-03 06:00:28
下面是我在简单的异步get ajax中经常使用的一个函数:
1.使用onload,因为它编写起来更短,而且不需要添加多个eventhandlers。
2.不要使用同步ajax。
js
function ajax(a,b,c){//url,function,just a placeholder
c=new XMLHttpRequest;
c.open('GET',a);
c.onload=b;
c.send()
}
function alertTxt(){
alert(this.response)
}
window.onload=function(){
ajax('hello.txt',alertTxt)
}
示例
额外信息
https://stackoverflow.com/a/18309057/2450730
完整的html
<html><head><script>
function ajax(a,b,c){//url,function,just a placeholder
c=new XMLHttpRequest;
c.open('GET',a);
c.onload=b;
c.send()
}
function alertTxt(){
alert(this.response)
}
window.onload=function(){
ajax('hello.txt',alertTxt)
}
</script></head><body></body></html>
发布于 2020-01-13 22:18:09
这就是你的答案。
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var allText = this.responseText;
alert(allText);
}
};
xhttp.open("GET", "filename.txt", true);
xhttp.send();
发布于 2020-02-27 14:46:16
下面的代码可能对某些人有用...
<!DOCTYPE html>
<html>
<body>
<h1>Load Data from text file </h1>
<button type="button" onclick="loadDoc()">Change Content</button>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "info.txt", true);
xhttp.send();
document.getElementById("demo").innerHTML = xhttp.responseText;
}
</script>
</body>
</html>
https://stackoverflow.com/questions/19747288
复制相似问题