settingsAccountsettings
Menusettings

Q: XHR (XmlHttpRequest task)

+2 votes

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:

xhr task

asked in JavaScript category by user andrew

1 Answer

+1 vote

Read more about XMLHttpRequest.open(): HERE

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();
}

 

answered by user eiorgert
edited by user eiorgert
...