< JavaScript AJAX

AJAX - Dolgozók REST API

Szerző: Sallai András

Copyright © Sallai András, 2023

Licenc: CC Attribution-Share Alike 4.0 International

Web: https://szit.hu

Bevezetés

XMLHttpRequest használata dolgozókkal.

GitHubon:

https://github.com/oktat/exemp_xhr

Kliens

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

Link

https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest (2023)