我想写一个简单的ajax局部刷新的例子,点击按钮后把一个txt文本文件的内容加载进来替换原有的内容,代码是这样的:
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","a.txt",true);
xmlhttp.send();
}
</script>
</head>
<body><h2>AJAX</h2>
<button type="button" onclick="loadXMLDoc()">请求数据</button>
<div id="myDiv"></div></body>
</html>
这个html文件和txt文件在同一个文件夹下,不知道什么原因实现不了,请指点,刚开始学习ajax,很多不懂的。
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","a.txt",true);
xmlhttp.send();
}
</script>
</head>
<body><h2>AJAX</h2>
<button type="button" onclick="loadXMLDoc()">请求数据</button>
<div id="myDiv"></div></body>
</html>
这个html文件和txt文件在同一个文件夹下,不知道什么原因实现不了,请指点,刚开始学习ajax,很多不懂的。
解决方案 »
- 关于一个简单函数执行中非常奇怪的问题
- JavaScript问题,请高手指教
- Ext饼图显示数值问题?
- javascript 中的正则表达式及||运算(高手请进)
- 本人新手,单击显隐层的问题
- 正则表达式 路径支持中文
- js放大镜
- javascript中给session赋值
- 请教:htm网页文件上播放Flash文件,但需要定时更换? Asp页面也行
- Javascript里面利用动态增加表格行来输入数据,但是提交之后再返回(按IE里面的BACK),数据全部丢失,怎么来处理?
- ckeditor编辑器的CSS被ext4的css“污染”,造成选择框变型,求好的解决方案
- 用js写一个封装类,怎么通过对象赋值的方式进行类的实例化
<div id="myDiv"></div>
<script language="javascript" type="text/javascript">
function loadXMLDoc(){
var xmlhttp = false;
if (window.XMLHttpRequest)xmlhttp = new XMLHttpRequest(); else if (window.ActiveXObject) {
var B = ["MSXML2.XMLHTTP", "Microsoft.XMLHTTP", "MSXML2.XMLHTTP.5.0", "MSXML2.XMLHTTP.4.0", "MSXML2.XMLHTTP.3.0"];
for (var C = 0; C < B.length; C++) {
try {
xmlhttp = new ActiveXObject(B[C]);
break
} catch (F) {
alert("不支持 AJAX!")
}
}
}
if (xmlhttp) {
xmlhttp.open( "GET","a.txt", true);
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
};
xmlhttp.send(null);
}
}
</script>
同时注意,ajax必须在网络中运行,不能是本地运行。比如你打开 D:\newsSite\test\0.html 运行ajax会提示拒绝访问,必须用 http://访问