简体   繁体   English

XMLHttpRequest responseText打开本地txt文件时为空

[英]XMLHttpRequest responseText empty when opening a local txt file

It's an example from "DOM Scripting Web Design With js the Document Object Model" ajax.html: 这是“使用js的DOM脚本进行Web设计文档对象模型”示例的一个示例: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 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 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 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);

the example.txt and the ajax.html are in the same dir,and the request.status=0 , the responseText is always empty.What's wrong with my code? example.txtajax.html在同一目录中,而request.status=0responseText始终为空。我的代码有什么问题?

I met the same problem when I am using chrome or IE. 我在使用chrome或IE时遇到了同样的问题。 However, when I switch to Firefox, it's amazingly all right! 但是,当我切换到Firefox时,一切都非常好! Someone said that it's because that Ajax is based on HTTP protocol. 有人说这是因为Ajax基于HTTP协议。 IE or chrome will have errors between HTTP and FILE protocol. IE或chrome在HTTP和FILE协议之间会有错误。 Firefox can be compatible (the details is too complicated for me), so I just suggest using Firefox~ Also please check no typo errors in your script. Firefox可以兼容(细节对我来说太复杂了),所以我只建议使用Firefox〜也请检查脚本中是否没有拼写错误。

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

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