[解決済] XHR (XmlHttpRequest task)

  

3
トピックスターター

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

1件の回答
2

Read more about XMLHttpRequest.open(): こちら

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