简单的AJAX示例-从txt文件加载数据 [英] Simple AJAX example - load data from txt file
本文介绍了简单的AJAX示例-从txt文件加载数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试做一个基本的AJAX教程,以从文件hello.txt中读取数据到我的网页中.hello.txt和我当前的html网页位于同一目录中.有人知道我在做什么错吗?加载页面没有任何反应.
I'm trying to do a basic AJAX tutorial to read data from a file, hello.txt, into my webpage. hello.txt and my current html webpage are in the same directory. Does anyone know what I'm doing wrong? Nothing happens when I load the page.
<!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>
推荐答案
这是我一直用于简单异步获取ajax的函数:
here is a function i always use for simple async get ajax:
1.使用onload是因为它的编写时间较短,并且不需要添加多个事件处理程序.
1.use onload as it's shorter to write and as you don't need to add multiple eventhandlers.
2.不要做同步ajax.
2.don't do syncronous 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>
这篇关于简单的AJAX示例-从txt文件加载数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文