Tartalomjegyzék

< JavaScript AJAX

AJAX - Dolgozók REST API

Bevezetés

XMLHttpRequest használata dolgozókkal.

GitHubon:

Kliens

src/index.html
<!DOCTYPE html>
<html lang="hu">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>xhr</title>
    <link rel="stylesheet" href="bootstrap.css">
</head>
<body>
 
    <div class="container">
        <h1>Dolgozók</h1>
 
        <table class="table table-striped">
            <thead>
                <tr>
                    <th>Id</th>
                    <th>Név</th>
                    <th>Település</th>
                    <th>Fizetés</th>
                </tr>
            </thead>
            <tbody id="tbody"></tbody>
        </table>
 
    </div>
    <script src="app.js"></script>
</body>
</html>
src/app.js
const host = 'http://localhost:3000/';
 
function getEmployees() {
    let endpoint = 'employees';
    let url = host + endpoint;
    let http = new XMLHttpRequest();
    http.open('get', url);
    http.send();    
    http.addEventListener('load', () => {
        let emps = http.responseText;
        renderTable(JSON.parse(emps));
    });
}
 
function renderTable(employees) {
    employees.forEach(emp => {
        let tr = document.createElement('tr');
        let tdId = document.createElement('td');
        let tdName = document.createElement('td');
        let tdCity = document.createElement('td');
        let tdSalary = document.createElement('td');
 
        tdId.textContent = emp.id;
        tdName.textContent = emp.name;
        tdCity.textContent = emp.city;
        tdSalary.textContent = emp.salary;
 
        document.getElementById('tbody').append(tr);
        tr.append(tdId);
        tr.append(tdName);
        tr.append(tdCity);
        tr.append(tdSalary);
 
    });
 
}
 
getEmployees();