我现在文本里面有写内容,想通过AJAX加载TXT文本里面的内容,现在出现拒绝访问
不知道是什么原因
<head>
<script type="text/javascript">
var xmlhttp;
function loadXMLDoc(url)
{
xmlhttp=null;
if(window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else if(window.ActiveXObject)
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
if(xmlhttp!=null)
{
xmlhttp.onreadystatechange=state_Change;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}
}
function state_Change()
{
if(xmlhttp.readystate==4) // 4 == "loaded"
{
if(xmlhttp.status==200) // 200 == "OK"
{
document.getElementById("text").innerHTML=xmlhttp.responseText;
}
}
else
{
alert("Problem retrieving data:"+xmlhttp.statusText);
}
}
</script>
</head>
<body onload="loadXMLDoc('2.txt');">
<div id="text" style="border:1px solid #ff0000; height:80px; width:400px;"></div></br>
<input type="button" value="单击" onClick="loadXMLDoc('1.txt');"></input>
</body>
不知道是什么原因
<head>
<script type="text/javascript">
var xmlhttp;
function loadXMLDoc(url)
{
xmlhttp=null;
if(window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else if(window.ActiveXObject)
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
if(xmlhttp!=null)
{
xmlhttp.onreadystatechange=state_Change;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}
}
function state_Change()
{
if(xmlhttp.readystate==4) // 4 == "loaded"
{
if(xmlhttp.status==200) // 200 == "OK"
{
document.getElementById("text").innerHTML=xmlhttp.responseText;
}
}
else
{
alert("Problem retrieving data:"+xmlhttp.statusText);
}
}
</script>
</head>
<body onload="loadXMLDoc('2.txt');">
<div id="text" style="border:1px solid #ff0000; height:80px; width:400px;"></div></br>
<input type="button" value="单击" onClick="loadXMLDoc('1.txt');"></input>
</body>
url应该是一个可访问的页面,然后在该页面中读取2.txt中的内容,用Response.write方法返回到客户端。客户端再做处理。
楼主的方法应该没有错。看一下服务器侧的设置吧。
如果是服务器问题,你把url用浏览器直接打开看看是不是能打开,能打开就不是服务器问题.如果服务器返回是下载的话,那可能是服务器将txt设置成force-download了,那你js去读取的话就可能有问题了
那就是跨域问题了,就像7楼的,你的ajax代码所在页面是不是在同一个域名下
如:都是在 http://localhost/test/下即http://localhost/test/a.htm去open http://localhost/test/b.txt文件如果不是,那就是跨域问题
即http://localhost/test/a.htm去调取 http://www.google.com的内容,那一定是跨域了
同域是指: 协议相同,根目录也相同的即:http://localhost/a.htm http://localhost/test./b.txt是同域即都是localhost与http
不同域是如下:
http://localhost/a.htm与http://127.0.0.1/test.txt就是跨域
http://localhost/a.htm与https://localhost/test/b.txt是跨域
同意,把TXT文件后缀名改为 .htm 更好