js代码在firefox中工作而不是在chrome

时间:2015-10-06 07:39:46

标签: javascript html google-chrome

我是js的新手,我会创建一个小程序,它接受* .xml文件并以JSON格式给出响应。我的代码适用于Firefox,但不适用于IE和Chrome。我不知道为什么?

我的html / js代码:

<html> 
<head> </head>
<script type="text/javascript">
    function myFunction() {
        var code = document.getElementById('text_box').value;

        var xhttp = new XMLHttpRequest();

        xhttp.onreadystatechange = function() {
            if (xhttp.readyState == 4 && xhttp.status == 200) {
                mysecondFunction(xhttp);
            }
        }

        xhttp.open("GET", code, true);
        xhttp.send();

        function mysecondFunction(xml) {
        var xmlDoc = xml.responseXML;
        var x = xmlDoc.documentElement.children;
        var y =' '; 

        for( var i = 0; i < x.length; i++ ) {
            y += '\"'+ x[i].nodeName + '\"' + ": " + x[i].children.length + ',' + '<br>';
        }   

        if ( code.length > 0 ) {
            document.getElementById('demo').innerHTML = '{ ' + '<br>' + y + ' }';
            }
        }

        var result = document.getElementById('result');
        result.innerHTML = 'result: ' + code;
    }
</script>
<body>  
    <input type="text" name="text_box" id="text_box" placeholder="enter xml file url" />
    <input type="button" name="button_box" id="button_box" onclick="myFunction()" value="convert" />
    <div id="result">result: 
    </div>
    <p id="demo"></p>
</body> 

我的例子* xml文件:

<bookstore>
<book category="cooking">
    <title lang="en">Everyday Italian</title>
    <author>Giada De Laurentiis</author>
    <year>2005</year>
    <price>30.00</price>
</book>
<book category="children">
    <title lang="en">Harry Potter</title>
    <author>J K. Rowling</author>
    <year>2005</year>
    <price>29.99</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>
<book category="web" cover="paperback">
    <title lang="en">Learning XML</title>
    <author>Erik T. Ray</author>
    <year>2003</year>
    <price>39.95</price>
</book>

2 个答案:

答案 0 :(得分:0)

我认为你的问题的答案就在这里:

XMLHttpRequest Browser Support

我还建议您使用抽象库,例如jquery(http://jquery.com),以确保跨浏览器兼容性。

答案 1 :(得分:0)

In case you are using the local filesystem to store the XML file and you are facing the issue, the solution will be to store the Javascript file, HTML file and XML files in the same folder.

If you are accessing the XML file through a server and still facing the issue, please add the error description.