index.html 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <title>Document</title>
  8. </head>
  9. <style>
  10. #table ,tr , td {
  11. border: 3px solid black;
  12. border-collapse: collapse;
  13. font-size: 17px;
  14. text-transform: uppercase;
  15. }
  16. </style>
  17. <body>
  18. <table id="table">
  19. </table>
  20. <script>
  21. //fetch basic +++ fetch improved
  22. fetch('https://swapi.dev/api/people/1/')
  23. .then(res => res.json())
  24. .then(luke => createTable(document.getElementById("table"), luke))
  25. function createTable(dom , json ){
  26. let table = document.getElementById('table')
  27. table.style.border = '2px solid black'
  28. console.log(json)
  29. for( let [key , value] of Object.entries(json)){
  30. let trKey = document.createElement('tr')
  31. trKey.innerHTML = key
  32. table.append(trKey)
  33. let tdValue = document.createElement('td')
  34. trKey.append(tdValue)
  35. // tdValue.innerText = value
  36. if(typeof value === 'object'){
  37. for(val of value){
  38. let btn = document.createElement('button')
  39. btn.innerHTML = val
  40. btn.addEventListener('click' , function(){
  41. fetch(val).then(res => res.json()).then(luke => createTable(this.parentNode, luke))
  42. })
  43. tdValue.append(btn)
  44. }
  45. }else{
  46. let btn = document.createElement('button')
  47. btn.innerHTML = value
  48. tdValue.append(btn)
  49. }
  50. }
  51. }
  52. //myfetch
  53. function myfetch(url){
  54. return new Promise(function(resolve,reject){
  55. let xhr = new XMLHttpRequest()
  56. xhr.open('GET' , url , true)
  57. xhr.send();
  58. xhr.onreadystatechange = (e) => {
  59. if (xhr.readyState != 4) {
  60. return;
  61. }
  62. if (xhr.status === 200) {
  63. resolve(JSON.parse(xhr.responseText));
  64. }
  65. reject("request error");
  66. };
  67. });
  68. }
  69. // myfetch('https://swapi.dev/api/people/1/')
  70. // .then(luke => createTable(document.getElementById("myFetch") , luke))
  71. //race
  72. const random = (min, max) => {
  73. return Math.floor(Math.random() * (max - min + 1)) + min;
  74. }
  75. let delay = (ms) => setTimeout(() =>console.log("delay"), ms);
  76. Promise.race([myfetch('https://swapi.dev/api/people/1/').then(luke => console.log(luke)), delay(random(10, 200))])
  77. </script>
  78. </body>
  79. </html>