简体   繁体   中英

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:

<!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);

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?

I met the same problem when I am using chrome or IE. However, when I switch to Firefox, it's amazingly all right! Someone said that it's because that Ajax is based on HTTP protocol. IE or chrome will have errors between HTTP and FILE protocol. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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