0

Can you explain me the difference between these code blocks?

I can't get it!


 $('document').ready(function(){
        var str;

        var request= new XMLHttpRequest();
        request.open('get','http://localhost:8080/new/text.jsp',true);
        request.onload=function(){
            str=request.responseText;

        };
        request.send();
        $('h1').text(str);
    });

$('document').ready(function(){
    var str;

    var request= new XMLHttpRequest();
    request.open('get','http://localhost:8080/new/text.jsp',true);
    request.onload=function(){
        str=request.responseText;   
        $('h1').text(str);
    };
    request.send();
});
Marco Salerno
  • 5,131
  • 2
  • 12
  • 32
김진오
  • 49
  • 4

1 Answers1

2

This because an Ajax request (XMLHttpRequest) executes async. The onload function is triggered when you get a response. In the response you do need to check for status code and response code.

The first piece of code. Does not wait for the response but just puts str in to the h1. The second piece of code wait for the request to process and when you get a response it will use that code into the h1.

Niels
  • 48,601
  • 4
  • 62
  • 81