Pulse7
8/19/2017 - 1:16 PM

XmlHttpRequest basic example

XmlHttpRequest basic example

import {Observable} from "rxjs";

let output = document.getElementById("output");
let button = document.getElementById("button");

let click = Observable.fromEvent(button,"click");

function load(url:string){
    let xhr = new XMLHttpRequest();

    xhr.addEventListener("load",()=>{
        let movies = JSON.parse(xhr.responseText);
        movies.forEach(m=>{
            let div = document.createElement("div");
            div.innerHTML = m.title;
            output.appendChild(div);
        });
    });

    xhr.open("GET",url);
    xhr.send();
}

click.subscribe(
    e=>load("movies.json"),
    e=>console.log(`error: ${e}`),
    ()=>console.log("complete")
);
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Document</title>
    <style>
        #circle{
            width: 20px;
            height: 20px;
            border-radius: 50%;
            background-color: red;
            position: absolute;
        }
    </style>
</head>
<body>
    <button id="button">Get Movies</button>
    <div id="output"></div>
<script src="app.js"></script>
</body>
</html>
[
    {
        "title":"Star Wars"
    },
    {
        "title":"Star Trek"
    },
    {
        "title":"Starship Troopers"
    }
]