jquery中ajax完整例子
jQuery AJAX 完整示例
以下是一个完整的 jQuery AJAX 请求示例,涵盖 GET 和 POST 请求的常见用法,包括成功和错误处理。

GET 请求示例
$.ajax({
url: 'https://api.example.com/data',
type: 'GET',
dataType: 'json',
success: function(response) {
console.log('请求成功:', response);
},
error: function(xhr, status, error) {
console.error('请求失败:', status, error);
}
});
POST 请求示例
$.ajax({
url: 'https://api.example.com/submit',
type: 'POST',
dataType: 'json',
data: {
name: 'John Doe',
email: 'john@example.com'
},
success: function(response) {
console.log('提交成功:', response);
},
error: function(xhr, status, error) {
console.error('提交失败:', status, error);
}
});
设置请求头
$.ajax({
url: 'https://api.example.com/auth',
type: 'GET',
dataType: 'json',
headers: {
'Authorization': 'Bearer your_token_here'
},
success: function(response) {
console.log('认证成功:', response);
},
error: function(xhr, status, error) {
console.error('认证失败:', status, error);
}
});
使用 Promise 风格
$.ajax({
url: 'https://api.example.com/data',
type: 'GET',
dataType: 'json'
}).done(function(response) {
console.log('请求成功:', response);
}).fail(function(xhr, status, error) {
console.error('请求失败:', status, error);
});
全局 AJAX 设置
$.ajaxSetup({
timeout: 5000,
beforeSend: function(xhr) {
console.log('请求即将发送');
},
complete: function() {
console.log('请求完成');
}
});
这些示例覆盖了 jQuery AJAX 的基本用法,包括请求类型、数据处理、错误处理和全局配置。根据实际需求调整参数即可。






