简体   繁体   中英

Ajax XmlHttpRequest

I have js code as well as *.txt file with some text that I want to load to the page.

JS Code:

 (function () {
 var link = document.getElementsByTagName("a")[0];
 link.onclick = function () {
      var xhr = new XmlHttpRequest();
      xhr.onreadystatechange = function () {
         if ((xhr.readyState == 4) && (xhr.status == 200 || xhr.status == 304)) {
                xhr.responseText;
                var body = document.getElementsByTagName("body")[0];
                var p = document.createElement("p");
                var pText = document.createTextNode(xhr.responseText);
                p.appendChild(pText);
                body.appendChild(p);
            }
        };
        xhr.open("Get", "ajax.txt", true);
        hxr.send(null);
        return false;
    };
})();

HTML Code:

<body>
<h1>AjaxTest</h1>
<a href="ajax.txt">Load the text from file</a>
<script src="main.js">
</script>

Everything should work. However ReSharper underlines XmlHttpRequest(); and says Use of an implicitly declared global variable" and for this xhr.responseText; it says - Expression statement is not assignment of call. What is the problem?

A few comments:

  • Capitalize "XML":

    var xhr = new XmlHttpRequest(); -> var xhr = new XMLHttpRequest();


  • A variable is not a statement:

    xhr.responseText; , just get rid of this line, it's like saying var a = 5; and then a;


  • You can use document.body to get the body element:

    var body = document.getElementsByTagName("body")[0]; ->

    var body = document.body;


  • You have no variable named hxr :

    hxr.send(null); -> xhr.send(null);


If you're following this is what you should get:

 (function () {
 var link = document.getElementsByTagName("a")[0];
 link.onclick = function () {
      var xhr = new XMLHttpRequest();
      xhr.onreadystatechange = function() {
         if ((xhr.readyState == 4) && (xhr.status == 200 || xhr.status == 304)) {
                var body = document.body;
                var p = document.createElement("p");
                var pText = document.createTextNode(xhr.responseText);
                p.appendChild(pText);
                body.appendChild(p);
            }
        };
        xhr.open("Get", "ajax.txt", true);
        xhr.send(null);
        return false;
    };
})();

If I were you I'd prefer using jQuery:

$('a').first().click(function() {
    $.get('ajax.txt', function(data) {
        $(document.body).append('<p>' + data + '</p>');
    });
});

This is your entire code using jquery ;)

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