jQuery 请求接口
约 614 字大约 2 分钟
2025-01-23
jQuery 是一个快速、小型且功能丰富的 JavaScript 库。它通过可在多种浏览器中运行的易于使用的 API 使 HTML 文档遍历和操作、事件处理、动画和 Ajax 等操作变得更加简单。jQuery 结合了多功能性和可扩展性,改变了数百万人编写 JavaScript 的方式。
jQuery 的 ajax()
方法是一个用于发送 HTTP 请求的函数。它接受一个配置对象作为参数,该对象可以包含请求的类型、URL、数据、回调函数等信息。ajax()
方法返回一个 jqXHR
对象,该对象表示一个异步请求。
使用
基本使用
$.ajax({
url: 'https://api.example.com/data', // 请求的 URL
type: 'GET', // HTTP 请求类型(GET/POST/PUT/DELETE)
dataType: 'json', // 服务器返回的数据类型(json/xml/html/text/script)
data: { id: 123 }, // 发送到服务器的数据(对象或字符串)
success: function(response) { // 请求成功时的回调
console.log(response);
},
error: function(xhr, status, error) { // 请求失败时的回调
console.error('Error:', error);
},
complete: function() { // 请求完成(无论成功或失败)
console.log('Request completed');
}
});
提示 $.ajax()
是最底层、最灵活的 AJAX 方法,还有简化版本,如:$.get()
和 $.post()
等。
GET 请求
$.ajax({
url: 'https://api.example.com/users',
type: 'GET',
dataType: 'json',
success: function(data) {
console.log('User data:', data);
},
error: function(xhr, status, error) {
console.error('Failed to fetch user data:', error);
}
});
设置请求头
$.ajax({
url: 'https://api.example.com/data',
type: 'GET',
headers: {
'Authorization': 'Bearer my-token',
'Custom-Header': 'my-value'
},
success: function(response) {
console.log(response);
}
});
请求超时设置
$.ajax({
url: '/slow-endpoint',
timeout: 5000, // 5 秒超时
success: function(response) {
console.log(response);
},
error: function(xhr, status, error) {
if (status === 'timeout') {
console.error('Request timed out');
}
}
});
错误处理
$.ajax({
url: 'https://api.example.com/error',
type: 'GET',
success: function(response) {
console.log(response);
},
error: function(xhr, status, error) {
console.error('Request failed:', status, error);
console.error('Response text:', xhr.responseText);
}
});
同步请求
$.ajax({
url: '/api/blocking',
async: false, // 设置为同步请求
success: function(response) {
console.log(response);
}
});
console.log('同步请求完成后执行');
因为底层使用的是 XMLHttpRequest,所以是支持同步请求的。但同步请求会阻塞浏览器,不建议使用。
全局 AJAX 事件
$(document).ajaxStart(function() {
console.log('AJAX request started');
});
$(document).ajaxStop(function() {
console.log('All AJAX requests completed');
});
$(document).ajaxError(function(event, xhr, settings, error) {
console.error('AJAX error:', error);
});
POST 请求(发送 JSON 数据)
$.ajax({
url: 'https://api.example.com/users',
type: 'POST',
contentType: 'application/json', // 指定请求内容类型
data: JSON.stringify({
username: 'john_doe',
email: 'john@example.com'
}),
success: function(response) {
console.log('User created:', response);
},
error: function(xhr, status, error) {
console.error('Failed to create user:', error);
}
});