Page 58 - JavaScript
P. 58

Chapter 3: AJAX




        Introduction



        AJAX stands for "Asynchronous JavaScript and XML". Although the name includes XML, JSON is
        more often used due to it's simpler formatting and lower redundancy. AJAX allows the user to
        communicate with external resources without reloading the webpage.


        Remarks



        AJAX stands for Asynchronous JavaScript and XML. Nevertheless you can actually use other
        types of data and—in the case of xmlhttprequest—switch to the deprecated synchronous mode.

        AJAX allows web pages to send HTTP requests to the server and receive a response, without
        needing to reload the entire page.


        Examples



        Using GET and no parameters



         var xhttp = new XMLHttpRequest();
         xhttp.onreadystatechange = function () {
             if (xhttp.readyState === XMLHttpRequest.DONE && xhttp.status === 200) {
                 //parse the response in xhttp.responseText;
             }
         };
         xhttp.open("GET", "ajax_info.txt", true);
         xhttp.send();


        6

        The fetch API is a newer promise-based way to make asynchronous HTTP requests.


         fetch('/').then(response => response.text()).then(text => {
           console.log("The home page is " + text.length + " characters long.");
         });


        Sending and Receiving JSON Data via POST


        6


        Fetch request promises initially return Response objects. These will provide response header
        information, but they don't directly include the response body, which may not have even loaded
        yet. Methods on the Response object such as .json() can be used to wait for the response body
        to load, then parse it.






        https://riptutorial.com/                                                                               15
   53   54   55   56   57   58   59   60   61   62   63