3
22/10/2024 4:17 pm
Emne starter
Your task is to write a JS function that loads a github repository asynchronously with AJAX. You should create an instance of XmlHttpRequest an attach an onreadystatechange event to it. (An EventHandler that is called whenever the readyState attribute changes). In your event handler when the readyState attribute reaches a value of 4 (it is ready), replace the text content of a div element with id "res" with the value of the responseText property of the request. Do not format the response in any way.
HTML Skeleton:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>XmlHttpRequest Example</title> <script src="scripts/1.xhr.js"></script> </head> <body> <button onclick="loadRepos()">Load Repos</button> <div id="res"></div> <script> function loadRepos() { // TODO } </script> </body> </html>
Example:
1 Answer
2
22/10/2024 4:18 pm
Read more about XMLHttpRequest.open(): HER
Here is the solution HTML + the script:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <button onclick="loadRepos()">Load</button> <div id="res"></div> <script> function loadRepos() { let req = new XMLHttpRequest(); req.onreadystatechange = function () { if (this.readyState == 4 && this.status == 200) { document.getElementById("res").textContent = this.responseText; } }; req.open("GET", "https://api.github.com/users/testnakov/repos", true); req.send(); } </script> </body> </html>
Only the script:
function loadRepos() { let req = new XMLHttpRequest(); req.onreadystatechange = function () { if (this.readyState == 4 && this.status == 200) { document.getElementById("res").textContent = this.responseText; } }; req.open("GET", "https://api.github.com/users/testnakov/repos", true); req.send(); }
Vennligst Logg inn eller Registrer deg for å svare på dette emnet.