首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >简单的AJAX示例-从txt文件加载数据

简单的AJAX示例-从txt文件加载数据
EN

Stack Overflow用户
提问于 2013-11-03 05:51:36
回答 5查看 21K关注 0票数 4

我正在尝试做一个基本的AJAX教程,将文件hello.txt中的数据读取到我的网页中。hello.txt和我当前的html网页在同一个目录中。有人知道我做错了什么吗?当我加载页面时,没有任何反应。

代码语言:javascript
复制
<!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>
EN

回答 5

Stack Overflow用户

发布于 2013-11-03 06:00:28

下面是我在简单的异步get ajax中经常使用的一个函数:

1.使用onload,因为它编写起来更短,而且不需要添加多个eventhandlers。

2.不要使用同步ajax。

js

代码语言:javascript
复制
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)
}

示例

http://jsfiddle.net/9pCxp/

额外信息

https://stackoverflow.com/a/18309057/2450730

完整的html

代码语言:javascript
复制
<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>
票数 1
EN

Stack Overflow用户

发布于 2020-01-13 22:18:09

这就是你的答案。

代码语言:javascript
复制
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();
票数 0
EN

Stack Overflow用户

发布于 2020-02-27 14:46:16

下面的代码可能对某些人有用...

代码语言:javascript
复制
 <!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>
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19747288

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档