简体   繁体   English

XMLHttpRequest 不工作(空白页)

[英]XMLHttpRequest not working (blank page)

I copied this code from W3Schools (along with the original XML file cd_catalog.xml) and I'm getting a blank page:我从 W3Schools 复制了这段代码(连同原始的 XML 文件 cd_catalog.xml),我得到了一个空白页面:

<html>
<body>

<script type="text/javascript">
    if (window.XMLHttpRequest)
    {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    }
    else
    {// code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.open("GET","cd_catalog.xml",false);
    xmlhttp.send();
    xmlDoc=xmlhttp.responseXML;

    document.write("<table border='1'>");
    var x=xmlDoc.getElementsByTagName("CD");
    for (i=0;i<x.length;i++)
    {
        document.write("<tr><td>");
        document.write(x[i].getElementsByTagName("ARTIST")[0].childNodes[0].nodeValue);
        document.write("</td><td>");
        document.write(x[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue);
        document.write("</td></tr>");
    }
    document.write("</table>");
</script>

</body>
</html>

I tried Opera, Firefox, IE and Chrome.我尝试了 Opera、Firefox、IE 和 Chrome。 Nothing.没有什么。 :( :(

Since you're not using a web server try doing this:由于您没有使用网络服务器,请尝试执行以下操作:

xmlhttp.open("GET","file:///C:/cd_catalog.xml", false);

You may end up needing a web server because the browsers will not allow your script access to the local files, eg see discussion here: http://www.webdeveloper.com/forum/showthread.php?t=233306您可能最终需要一个 Web 服务器,因为浏览器不允许您的脚本访问本地文件,例如,请参阅此处的讨论: http : //www.webdeveloper.com/forum/showthread.php?t=233306

So consider setting up a simple web server on your machine, like lighttpd .所以考虑在你的机器上设置一个简单的网络服务器,比如lighttpd

EDIT: the way I interpret the spec ( http://dvcs.w3.org/hg/xhr/raw-file/tip/Overview.html#the-open%28%29-method ) is that this must be done through HTTP.编辑:我解释规范的方式( http://dvcs.w3.org/hg/xhr/raw-file/tip/Overview.html#the-open%28%29-method )是这必须通过HTTP。 It's not absolutely clear though.不过也不是很清楚。 A file: URL may not be allowed in this context so the expectation is that the code snippet above may not work and you will need a web server. A file: URL 在此上下文中可能不被允许,因此预期上面的代码片段可能不起作用,您将需要一个 Web 服务器。

A related question is:一个相关的问题是:

Read file:// URLs in IE XMLHttpRequest 在 IE XMLHttpRequest 中读取 file:// URLs

and

Allow Google Chrome to use XMLHttpRequest to load a URL from a local file 允许 Google Chrome 使用 XMLHttpRequest 从本地文件加载 URL

Upload your code to a web server.将您的代码上传到 Web 服务器。 You will get the desired output on all browsers such as IE, Chrome, or Mozilla.您将在所有浏览器(如 IE、Chrome 或 Mozilla)上获得所需的输出。 But if you try this same code on the local machine, then IE and Chrome won't work.但是如果你在本地机器上尝试同样的代码,那么 IE 和 Chrome 将无法工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM