admin管理员组

文章数量:1318031

I'm trying to do a basic AJAX tutorial to read data from a file, hello.txt, into my webpage. hello.txt and my current html webpage are in the same directory. Does anyone know what I'm doing wrong? Nothing happens when I load the page.

<!DOCTYPE html>
<head><title>Ajax Test</title>
<script type="text/javascript">
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.open("GET", "hello.txt", true);
    xmlHttp.addEventListener("load", ajaxCallback, false);
    xmlHttp.send(null);
    function ajaxCallback(event){
        alert( "Your file contains the text: " + event.target.responseText );
    }

</script>
</head>
<body>
</body>
</html>

I'm trying to do a basic AJAX tutorial to read data from a file, hello.txt, into my webpage. hello.txt and my current html webpage are in the same directory. Does anyone know what I'm doing wrong? Nothing happens when I load the page.

<!DOCTYPE html>
<head><title>Ajax Test</title>
<script type="text/javascript">
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.open("GET", "hello.txt", true);
    xmlHttp.addEventListener("load", ajaxCallback, false);
    xmlHttp.send(null);
    function ajaxCallback(event){
        alert( "Your file contains the text: " + event.target.responseText );
    }

</script>
</head>
<body>
</body>
</html>
Share Improve this question asked Nov 2, 2013 at 21:51 SpannerSpanner 411 gold badge1 silver badge4 bronze badges 3
  • Is your textfile located under http://example./hello.txt where the request es from http://example.? – Sumurai8 Commented Nov 2, 2013 at 22:02
  • I just saved it in the same folder as my html file. When I upload it to my server my html page is example./~user/test.html and my textfile is example./~user/hello.txt – Spanner Commented Nov 2, 2013 at 22:05
  • 2 Your code works flawlessly on latest FF & Chrome. – nietonfir Commented Nov 2, 2013 at 23:05
Add a ment  | 

5 Answers 5

Reset to default 1

here is a function i always use for simple async get ajax:

1.use onload as it's shorter to write and as you don't need to add multiple eventhandlers.

2.don't do syncronous ajax.

js

function ajax(a,b,c){//url,function,just a placeholder
 c=new XMLHttpRequest;
 c.open('GET',a);
 c.onload=b;
 c.send()
}

function alertTxt(){
 alert(this.response)
}

window.onload=function(){
 ajax('hello.txt',alertTxt)
}

example

http://jsfiddle/9pCxp/

extra info

https://stackoverflow./a/18309057/2450730

full html

<html><head><script>
function ajax(a,b,c){//url,function,just a placeholder
 c=new XMLHttpRequest;
 c.open('GET',a);
 c.onload=b;
 c.send()
}

function alertTxt(){
 alert(this.response)
}

window.onload=function(){
 ajax('hello.txt',alertTxt)
}
</script></head><body></body></html>

Here is your answer.

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
    if (this.readyState == 4 && this.status == 200) {
        var allText = this.responseText;
        alert(allText);
    }
};
xhttp.open("GET", "filename.txt", true);
xhttp.send();

The below code may be useful for someone...

 <!DOCTYPE html>
 <html>
 <body>

 <h1>Load Data from text file </h1>

 <button type="button" onclick="loadDoc()">Change Content</button>

 <script>
     function loadDoc() {
       var xhttp = new XMLHttpRequest();
       xhttp.open("GET", "info.txt", true);
       xhttp.send();
       document.getElementById("demo").innerHTML = xhttp.responseText;
     }
 </script>

 </body>
 </html>

Open an empty .PHP file or .ASPX file (or just any server-side language that can run javascript)

Paste this code between "head" tags.

<script>
    var xmlhttp;
    function loadXMLDoc(url, cfunc) {
        if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
        }
        else {// code for IE6, IE5
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.onreadystatechange = cfunc;
        xmlhttp.open("GET", url, true);
        xmlhttp.send();
    }
    function myFunction() {
        loadXMLDoc("hello.xml", function () {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
            }
        });
    }
</script>

As you see, javascript is referring to "hello.xml" file to get information from.

Open an empty XML file inside the project folder you have created in. Name your XML file as "hello.xml"

Paste this code to your XML file.

<?xml version="1.0" encoding="utf-8"?>
<note>
  <to>Tove</to>
  <from>Jani</from>
  <heading>Reminder</heading>
  <body>Don't forget me this weekend!</body>
</note>

Run your php (or .aspx) file on localhost.

Click on button, your page must acquire the XML data into your website.

    function Go() {

        this.method = "GET";
        this.url = "hello.txt";

        if (window.XMLHttpRequest && !(window.ActiveXObject)) {
            try {
                this.xmlhttp = new XMLHttpRequest();
            }
            catch (e) {
                this.xmlhttp = false;
            }
            // branch for IE/Windows ActiveX version
        }
        else if (window.ActiveXObject) {
            try {
                this.xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
            }
            catch (e) {
                try {
                    this.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
                }
                catch (e) {
                    this.xmlhttp = false;
                }
            }
        }

        if (this.xmlhttp) {

            var self = this;
            if (this.method == "POST") {
                this.xmlhttp.open("POST", this.url, true);
            }
            else {
                //remember - we have to do a GET here to retrive the txt file contents
                this.xmlhttp.open("GET", this.url, true);
            }


            this.xmlhttp.send(null);

            //wait for a response
            this.xmlhttp.onreadystatechange = function () {

                try {
                    if (self.xmlhttp.readyState == 4) {
                        if (self.xmlhttp.status == 200) {
                            if (self.xmlhttp.responseText != null) {
                                self.response = self.xmlhttp.responseText;

                                alert(self.xmlhttp.responseText);
                            }
                            else {
                                self.response = "";
                            }

                        }
                        else if (self.xmlhttp.status == 404) {
                            alert("Error occured. Status 404: Web resource not found.");
                        }
                        else if (self.xmlhttp.status == 500) {
                            self.showHtmlError("Internal server error occured", "Status: " + self.xmlhttp.responseText);
                        }
                        else {
                            alert("Unknown error occured. Status: " + self.xmlhttp.status);
                        }
                    }
                }
                catch (e) {
                    alert("Error occured. " + e.Description + ". Retry or Refresh the page");
                }
                finally {

                }
            };

        }
    }


    //Use the function in your HTML page like this:

    Go();

</script>

本文标签: javascriptSimple AJAX exampleload data from txt fileStack Overflow