$.ajax 异步用法
$.ajax
是 jQuery 库中用于执行异步 HTTP 请求的函数。它可以用来发送 GET、POST 等请求,并处理服务器返回的数据。以下是 $.ajax
的基本用法和一些常见的配置选项:
$.ajax({
url: 'https://api.example.com/data', // 请求的URL
type: 'GET', // 请求类型,常见的有 'GET' 和 'POST'
dataType: 'json', // 预期服务器返回的数据类型
success: function(response) {
// 请求成功时的回调函数
console.log(response);
},
error: function(xhr, status, error) {
// 请求失败时的回调函数
console.error('Error:', error);
}
});
url
: 请求的URL地址。type
: 请求类型(GET、POST、PUT、DELETE等)。data
: 发送到服务器的数据,可以是对象、字符串等。dataType
: 预期服务器返回的数据类型(如 json
、xml
、html
、text
)。success
: 请求成功时的回调函数。error
: 请求失败时的回调函数。async
: 是否异步请求,默认为 true
。timeout
: 设置请求超时时间(毫秒)。headers
: 设置请求头信息。$.ajax({
url: 'https://api.example.com/data',
type: 'GET',
dataType: 'json',
success: function(response) {
console.log('Data received:', response);
},
error: function(xhr, status, error) {
console.error('Error:', error);
}
});
$.ajax({
url: 'https://api.example.com/data',
type: 'POST',
data: {
key1: 'value1',
key2: 'value2'
},
dataType: 'json',
success: function(response) {
console.log('Data received:', response);
},
error: function(xhr, status, error) {
console.error('Error:', error);
}
});
$.ajax({
url: 'https://api.example.com/data',
type: 'GET',
headers: {
'Authorization': 'Bearer your-token',
'Custom-Header': 'CustomValue'
},
dataType: 'json',
success: function(response) {
console.log('Data received:', response);
},
error: function(xhr, status, error) {
console.error('Error:', error);
}
});
$.ajax({
url: 'https://api.example.com/data',
type: 'GET',
dataType: 'json',
timeout: 5000, // 5秒超时
success: function(response) {
console.log('Data received:', response);
},
error: function(xhr, status, error) {
if (status === 'timeout') {
console.error('Request timed out');
} else {
console.error('Error:', error);
}
}
});
默认情况下,$.ajax
是异步的。如果你需要同步请求,可以将 async
选项设置为 false
,但不推荐这样做,因为同步请求会阻塞浏览器的其他操作。
$.ajax({
url: 'https://api.example.com/data',
type: 'GET',
dataType: 'json',
async: false, // 同步请求
success: function(response) {
console.log('Data received:', response);
},
error: function(xhr, status, error) {
console.error('Error:', error);
}
});
希望这些示例和说明能帮助你更好地理解和使用 $.ajax
进行异步请求。