簡體   English   中英

簡單的 AJAX 示例 - 從 txt 文件加載數據

[英]Simple AJAX example - load data from txt file

我正在嘗試做一個基本的 AJAX 教程,以將文件 hello.txt 中的數據讀取到我的網頁中。 hello.txt 和我當前的 html 網頁在同一個目錄中。 有誰知道我做錯了什么? 當我加載頁面時沒有任何反應。

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

這是我一直用於簡單異步獲取 ajax 的函數:

1. 使用 onload ,因為它編寫起來更短,而且您不需要添加多個事件處理程序。

2.不要做同步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)
}

例子

http://jsfiddle.net/9pCxp/

額外信息

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

完整的 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>

這是你的答案。

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

以下代碼可能對某人有用...

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

打開一個空的 .PHP 文件或 .ASPX 文件(或任何可以運行 javascript 的服務器端語言)

將此代碼粘貼在“head”標簽之間。

<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>

如您所見,javascript 指的是要從中獲取信息的“hello.xml”文件。

在您創建的項目文件夾中打開一個空的 XML 文件。將您的 XML 文件命名為“hello.xml”

將此代碼粘貼到您的 XML 文件中。

<?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>

在本地主機上運行您的 php(或 .aspx)文件。

單擊按鈕,您的頁面必須將 XML 數據獲取到您的網站中。

    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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM