【问题标题】:XMLHttpRequest responseText empty when opening a local txt file打开本地txt文件时XMLHttpRequest responseText为空
【发布时间】:2017-06-30 21:47:10
【问题描述】:

这是来自“DOM Scripting Web Design With js the Document Object Model”的一个例子 ajax.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
        <title>Ajax</title>
</head>
<body>
    <div id="new"></div>
    <script src="scripts\addLoadEvent.js"></script>
    <script src="scripts\getHTTPObject.js"></script>
    <script src="scripts\getNewContent.js"></script>
</body>
</html>

addLoadEvent.js

function addLoadEvent(func)
{
    var oldonload = window.onload;
    if(typeof window.onload != 'function')
    {
        window.onload = func;
    }
    else{
        window.onload = function(){
            oldonload();
            func();
        }
    }
}

getHttpObject,js

function getHTTPObject()
{
    if(typeof XMLHttpRequest == 'undefined')
        XMLHttpRequest = function(){
            try{return new ActiveXObject('Msxml2.XMLHTTP.6.0');}
                catch (e) {}
            try{return new ActiveXObject('Msxml2.XMLHTTP.3.0');}
                catch (e) {}
            try{return new ActiveXObject('Msxml2.XMLHTTP');}
                catch (e) {}
            return false;
        }
        return new XMLHttpRequest();
}

getNewContent.js

function getNewContent()
{
    var request = getHTTPObject();
    if(request){
        request.open("GET","example.txt",true);
        request.onreadystatechange = function(){
            if(request.readyState == 4){
                if(request.status == 0){
                    var para = document.createElement("p");
                    var txt = document.createTextNode(request.responseText);
                    para.appendChild(txt);
                    document.getElementById('new').appendChild(para);
                }
            }
        };
        request.send(null);
    }else{
        alert('sorry,your browser doesn\'t support XMLHTTPRequest');
    }
}

addLoadEvent(getNewContent);

example.txt 和 ajax.html 在同一个目录中,request.status=0, responseText 始终为空。我的代码有什么问题?

【问题讨论】:

  • 浏览器就是这样滚动的。 XMLHttpRequest 中的 HTTP 应该给你一个提示……它不是 XMLFileRequest
  • 另外,不要使用反斜杠( \ ),使用正斜杠( / ),反斜杠是无效的,只能在纠正错误的浏览器中使用。

标签: javascript ajax


【解决方案1】:

我在使用 chrome 或 IE 时遇到了同样的问题。但是,当我切换到 Firefox 时,它却出奇的好!有人说是因为Ajax是基于HTTP协议的。 IE 或 chrome 会在 HTTP 和 FILE 协议之间出现错误。火狐可以兼容(细节对我来说太复杂了),所以我只是建议使用火狐~ 另外请检查您的脚本中是否有拼写错误。

【讨论】:

    猜你喜欢
    • 2014-02-04
    • 2011-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-27
    • 1970-01-01
    • 1970-01-01
    • 2012-07-07
    相关资源
    最近更新 更多