js 如何读取xml文档内容

JavaScript015

js 如何读取xml文档内容,第1张

请把下面的代码保存为 readxml.html

<html>

<head>

<script type="text/javascript">

var xmlhttp

function loadXMLDoc(url)

{

xmlhttp=null

if (window.XMLHttpRequest)

  {// code for IE7, Firefox, Opera, etc.

  xmlhttp=new XMLHttpRequest()

  }

else if (window.ActiveXObject)

  {// code for IE6, IE5

  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP")

  }

if (xmlhttp!=null)

  {

  xmlhttp.onreadystatechange=state_Change

  xmlhttp.open("GET",url,true)

  xmlhttp.send(null)

  }

else

  {

  alert("Your browser does not support XMLHTTP.")

  }

}

function state_Change()

{

if (xmlhttp.readyState==4)

  {// 4 = "loaded"

  if (xmlhttp.status==200)

    {// 200 = "OK"

    document.getElementById('A1').innerHTML=xmlhttp.status

    document.getElementById('A2').innerHTML=xmlhttp.statusText

    

    document.getElementById('A3').innerHTML=xmlhttp.responseText

    }

  else

    {

    alert("Problem retrieving XML data:" + xmlhttp.statusText)

    }

  }

}

</script>

</head>

<body>

<h2>Using the HttpRequest Object</h2>

<p><b>Status:</b>

<span id="A1"></span>

</p>

<p><b>Status text:</b>

<span id="A2"></span>

</p>

<p><b>Response:</b>

<br /><span id="A3"></span>

</p>

<button onclick="loadXMLDoc('note.xml')">Get XML</button>

</body>

</html>

请把下面的文件保存未  note.xml

<?xml version="1.0" encoding="ISO-8859-1"?>

<note>

<to>George</to>

<from>John</from>

<heading>Reminder</heading>

<body>Don't forget the meeting!</body>

</note>

js读取xml文件跨域 问题,可以使用以下几种方法:

1 通过jsonp跨域 : 在js中,我们直接用XMLHttpRequest请求不同域上的数据时,是不可以的。但是,在页面上引入不同域上的js脚本文件却是可以的,jsonp正是利用这个特性来实现的。代码如下:

2  通过修改document.domain来跨子域:有一个页面,它的地址是http://www.example.com/a.html  , 在这个页面里面有一个iframe,它的src是http://example.com/b.html, 很显然,这个页面与它里面的iframe框架是不同域的 ;document.domain就可以派上用场了,我们只要把http://www.example.com/a.html 和 http://example.com/b.html这两个页面的document.domain都设成相同的域名就可以了

3 使用window.name来进行跨域 : 每个页面对window.name都有读写的权限,window.name是持久存在一个窗口载入过的所有页面