ajax替换内容

<html>
<head>
<script type="text/javascript">
function loadXMLDoc()
{
	//定义变量 判断是否支持XMLHttpRequest控件 如果支持在变量xmlhttp变量实例化后放入 XMLHttpRequest 是针对较新的游览器可以用这个控件
        var xmlDoc;
	var xmlhttp;
	var txt,x,i;
	if (window.XMLHttpRequest)
  	{
  		xmlhttp=new XMLHttpRequest();
  	}
  	//否则 就在xmlhttp变量实例化后里放入ActiveXObject("Microsoft.XMLHTTP")是针对较老的游览器可以使用者个控件
	else
  	{
  		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
 	 }
 	//在xmlhttp里放好以后就调用 onreadystatechange=function() 存储函数(或函数名),每当 readyState 属性改变时,就会调用该函数。
	xmlhttp.onreadystatechange=function()
  	{
  		
 		 if (xmlhttp.readyState==4 && xmlhttp.status==200)
    	{
    		// 可以获得XML里面的内容 txt定义为空 x获得xmlDoc调用方法可返回带有指定标签名的对象的集合
   			xmlDoc=xmlhttp.responseXML;
    		txt="";
    		x=xmlDoc.getElementsByTagName("title");
    		//开始循环 txt是txt加上x的i循环数组从第一行开始获得节点的值
    		for (i=0;i<x.length;i++)
      		{
      			txt=txt + x[i].childNodes[0].nodeValue + "<br />";
     		}
     		//显示出myDiv的id里的 成功后将里面的内容给替换掉
   	 		document.getElementById("myDiv").innerHTML=txt;
    	}
  	}
  	//创建替换的路径
  	xmlhttp.open("GET","books.xml",true);
  	//发送请求替换
	xmlhttp.send();
}
</script>
</head>

<body>

<h2>My Book Collection:</h2>
<div id="myDiv"></div>
<button type="button" onclick="loadXMLDoc()">获得我的图书收藏列表</button>
 
</body>
</html>
<!--   Copyright w3school.com.cn  -->
<!--  W3School.com.cn bookstore example  -->
<bookstore>
    <book category="children">
        <title lang="en">Harry Potter</title>
        <author>J K. Rowling</author>
        <year>2005</year>
        <price>29.99</price>
    </book>
    <book category="cooking">
        <title lang="en">Everyday Italian</title>
        <author>Giada De Laurentiis</author>
        <year>2005</year>
        <price>30.00</price>
    </book>
    <book category="web" cover="paperback">
        <title lang="en">Learning XML</title>
        <author>Erik T. Ray</author>
        <year>2003</year>
        <price>39.95</price>
    </book>
    <book category="web">
        <title lang="en">XQuery Kick Start</title>
        <author>James McGovern</author>
        <author>Per Bothner</author>
        <author>Kurt Cagle</author>
        <author>James Linn</author>
        <author>Vaidyanathan Nagarajan</author>
        <year>2003</year>
        <price>49.99</price>
    </book>
</bookstore>

这个是xml文件

需要实现的是把获得我的图书收藏列表
点击按钮后替换成xml里面的书名 路径 文件名字都没有问题但是就是替换不了
问题出在xmlhttp.open("GET","books.xml",true); 说没办法访问
请问要怎么写这里
未命名.jpg

阅读 6.1k
2 个回答
新手上路,请多包涵

我去 注册真麻烦。。。

你在前面定义变量时 加个 var xmlDoc; 就行了。

检查你的路径,books.xml放在哪里了,现在的写法是相对路径,也就是说books.xml和html文件放一起才有用

-------------------------
你跨域了,因为安全考虑,ajax是不能跨域的,也就是说必须放在服务器中,比如说以本地127.0.0.1的地址访问,而不是file://这样

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进