js的xml文件是什么

JavaScript035

js的xml文件是什么,第1张

刚学习javascript,写一个小游戏做练习,现在想要做一个配置文件,练习一下XML的操作……

进入正题:

如下xml文件:profile.xml

XML/HTML

<?xml version="1.0" ?>

<configuration>

    <row>Hello</row>

    <col>word!</col>

</configuration>

在google搜索结果中出现频率比较高的一段代码:

javascript文件:test.js

JavaScript

var doc = loadXmlFile("profile.xml")

alert(doc.text)

function loadXmlFile(xmlFile){

  var xmlDom = null

  if (window.ActiveXObject){

    xmlDom = new ActiveXObject("Microsoft.XMLDOM")

    //xmlDom.loadXML(xmlFile)//如果用的是XML字符串

    xmlDom.load(xmlFile)//如果用的是xml文件。

  }else if (document.implementation && document.implementation.createDocument){

    var xmlhttp = new window.XMLHttpRequest()

    xmlhttp.open("GET", xmlFile, false)

    xmlhttp.send(null)

    xmlDom = xmlhttp.responseXML

  }else{

    xmlDom = null

  }

  return xmlDom

}

这个方法在IE下能正常输出“hello word”,IE9、以及IE9的IE7、IE8的兼容模式都正常。

但是在firefox下输出的是“undefined”

而Chrome下则无输出,提示 xmlhttp.send(null)这行 Uncaught Error: NETWORK_ERR:XMLHttpRequest Exception 101

还有一种方法是用JQuery

JavaScript code?

$.get('profile.xml',function(xml){    

        alert($(xml).text())    

    })

在Chrome下只弹出一个空警告框……

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是持久存在一个窗口载入过的所有页面