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