简体   繁体   中英

Simple AJAX example - load data from txt file

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>

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.net/9pCxp/

extra info

https://stackoverflow.com/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>

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