IE9中的XMLHTTPRequest“访问被拒绝”错误

时间:2014-10-03 03:39:28

标签: javascript xml xmlhttprequest internet-explorer-9

我用JavaScript编写一个小程序来读取本地XML文件中的数据。当我尝试加载此文件时,我收到来自IE9的错误说:

SCRIPT5: Access is denied

当我尝试在Chrome中加载相同内容时,我收到错误消息:

XMLHttpRequest cannot load file://... cross origin requests are only supported for HTTP

Uncaught NetworkError: Failed to execute 'send' on 'XMLHttpRequest': Failed to load 'file...

以下是我的代码:

<!DOCTYPE html>
<html>
<head>
    <h1 id="si">Search Input</h1>
    <button onclick="promptSearch()">Search By Vessel Name</button>
    <h1 id="sr">Search Result</h1>
<script>
    function loadXMLDoc(filename) {
        if (window.XMLHttpRequest) {
            xhttp=new XMLHttpRequest();
            }
        else { // for IE5 and IE6
            xhttp=new ActiveXObject("Microsoft.XMLHTTP");
            }
        xhttp.open("GET",filename,false);
        xhttp.send();
        return xhttp.responseXML;
        }
    function promptSearch() {
        var prmpt = window.prompt("PLease enter vessel name:", "Vessel Name");
        var search= prmpt.toLowerCase();        
        if(prmpt != null){
            document.getElementById("si").innerHTML = search;
        }
        document.getElementById("sr").innerHTML = searchData();
    }   
    function searchData() {
        xmlDoc=loadXMLDoc("vesselData.xml");
    }
</script>
</head>
</html>

1 个答案:

答案 0 :(得分:1)

出于安全原因,浏览器不允许页面中的JavaScript访问其周围的本地文件,除非您在HTTP Server上运行它。

您可以使用简单的HTTP Server,并解决您当前的问题。

您可以使用nodejs创建一个简单的HTTPServer,如图所示here