AJAX 让页面无需刷新即可获取数据。jQuery 对 XMLHttpRequest 做了封装,使用起来非常简洁。
本节要点
- $.get 发送 GET 请求,$.post 发送 POST 请求。
- dataType 指定响应类型,例如 json。
- 使用 done、fail、always 处理异步结果。
代码示例
$.ajax({
url: "/api/articles",
method: "GET",
dataType: "json"
})
.done(function (data) {
console.log(data);
})
.fail(function (xhr, status, error) {
console.error(error);
});