kenvantruong
5/19/2018 - 2:48 PM

Ajax -> Fetch Local JSON with Ajax

Ajax -> Fetch Local JSON with Ajax

    <button id="button1">Get User</button>
    <button id="button2">Get Users</button>
    <br><br>
    <h1>User</h1>
    <div id="user"></div>
    <h1>Users</h1>
    <div id="users"></div>

    <script>
        document.getElementById('button1').addEventListener('click',printThat);
        document.getElementById('button2').addEventListener('click',printThat2);


        function printThat(){
            var xhr = new XMLHttpRequest();
            xhr.open('GET','user.json',true);
            xhr.onload = function(){
                if(xhr.status == 200){
                    var user = JSON.parse(xhr.responseText);
                    var output = '';

                    output += '<ul>' +
                '<li>Id: '+user.id+'</li>' +
                '<li>Name: '+user.name+'</li>' +
                '<li>Email: '+user.email+'</li>' +
                '</ul>';

                document.getElementById('user').innerHTML = output;
                }
            }
            xhr.send();
        }



/////////////////// LoadUser2 ////////////////////////



function printThat2(){
            var xhr = new XMLHttpRequest();
            xhr.open('GET','user2.json',true);
            xhr.onload = function(){
                if(xhr.status == 200){
                    var users = JSON.parse(xhr.responseText);
                    var output = '';

                    for(var i in users) {
                    output += '<ul>' +
                        '<li>Id: '+users[i].id+'</li>' +
                        '<li>Name: '+users[i].name+'</li>' +
                        '<li>Email: '+users[i].email+'</li>' +
                        '</ul>';
                    }
                   

                document.getElementById('users').innerHTML = output;
                }
            }
            xhr.send();
        }

        //JSON.parse ability is to convert JSON file text into Javascript readable

        //Question: why do you have to assign a var = ''; with nothing in it
    </script>