Advertisement
avr39ripe

jsAJAXBasics

May 17th, 2021
227
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <!DOCTYPE html>
  2. <html lang="en" id="html">
  3. <head>
  4.     <meta charset="UTF-8">
  5.     <title>XHR</title>
  6.     <style>
  7.         html,
  8.         body {
  9.             display: flex;
  10.             align-items: center;
  11.             justify-content: center;
  12.         }
  13.  
  14.         .container {
  15.             display: flex;
  16.             flex-direction: column;
  17.             justify-content: center;
  18.             align-content: center;
  19.             align-items: center;
  20.             margin-top: 30px;
  21.             position: relative;
  22.         }
  23.     </style>
  24. </head>
  25. <body>
  26.     <div id="container" class="container">
  27.     </div>
  28.     <script>
  29.         'use strict'
  30.  
  31.         {
  32.             function processResponse(json)
  33.             {
  34.                 let users = JSON.parse(json);
  35.  
  36.                 if (users.length == 0) {
  37.                     console.log('No such user!');
  38.                 }
  39.  
  40.                 for (let user of users) {
  41.                     console.log(`uid: ${user.id} name: ${user.name} nickname: ${user.username}`);
  42.                 }
  43.             }
  44.  
  45.             let xhr = new XMLHttpRequest();
  46.             xhr.open('GET', 'https://jsonplaceholder.typicode.com/users?id=100');
  47.  
  48.             //xhr.addEventListener('readystatechange', function () {
  49.             //    //console.log(this.readyState);
  50.  
  51.             //    if (this.readyState == 4) {
  52.             //        if (this.status >= 400) {
  53.             //            console.log(`XHR ERROR! ${this.status}`);
  54.             //        }
  55.             //        else {
  56.             //            let users = JSON.parse(this.response);
  57.             //            //console.log(users);
  58.  
  59.             //            for (let user of users) {
  60.             //                console.log(`uid: ${user.id} name: ${user.name} nickname: ${user.username}`);
  61.             //            }
  62.             //        }
  63.             //    }
  64.             //});
  65.  
  66.             xhr.addEventListener('load', function () {
  67.                
  68.                 if (this.status >= 400) {
  69.                     console.log(`XHR ERROR! ${this.status}`);
  70.                 }
  71.                 else {
  72.                     processResponse(this.response);
  73.                 }
  74.                
  75.             });
  76.  
  77.             xhr.send();
  78.  
  79.  
  80.  
  81.         }
  82.        
  83.     </script>
  84. </body>
  85. </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement