Kịch bản thuyết trình: Slide 140
Mình tiếp tục với slide 140 về ví dụ minh họa – jQuery AJAX call API.
Giải thích:
$.ajax({...})→ Hàm jQuery để gọi API.url→ endpoint API (ở đây dùng API public jsonplaceholder).method→ phương thức HTTP (GET/POST/PUT/DELETE).success: function(data){...}→ callback chạy khi API trả dữ liệu thành công.error: function(){...}→ callback chạy khi API lỗi.Dữ liệu trả về (data) được dùng để hiển thị ra HTML.
Code minh họa:
$(document).ready(function(){
// Bind click event to the button
$("#btn").click(function(){
// Call public API using jQuery AJAX
$.ajax({
url: "https://jsonplaceholder.typicode.com/users/1",
method: "GET",
success: function(data){
// Display user name and email
$("#result").html("Name: " + data.name + "<br>Email: " + data.email);
},
error: function(){
$("#result").html("Error while fetching data.");
}
});
});
});
Như vậy là mình đã trình bày xong ví dụ về cách sử dụng jQuery AJAX để gọi API và hiển thị dữ liệu.