jQuery发送Ajax请求示例
https://cdn.jsdelivr.net/npm/jquery/dist/jquery.min.js
1. 基本GET请求
$.ajax({
url: '/api/data', // 请求地址
type: 'GET', // 请求方法
dataType: 'json', // 预期返回的数据类型
beforeSend:function(){
},
success: function(data) {
// 请求成功处理
console.log('获取数据成功:', data);
},
complete:function(){
},
error: function(xhr, status, error) {
// 请求失败处理
console.error('获取数据失败:', error);
}
});
2. 带参数的GET请求
$.ajax({
url: '/api/search',
type: 'GET',
data: { // 发送到服务器的数据
keyword: 'jQuery',
page: 1
},
dataType: 'json',
success: function(data) {
console.log('搜索结果:', data);
},
error: function(xhr, status, error) {
console.error('搜索失败:', error);
}
});
3. POST请求
$.ajax({
url: '/api/users',
type: 'POST',
contentType: 'application/json', // 发送JSON数据
data: JSON.stringify({ // 转换为JSON字符串
name: ' ',
age: 25,
email: ' '
}),
dataType: 'json',
success: function(data) {
console.log('创建用户成功:', data);
},
error: function(xhr, status, error) {
console.error('创建用户失败:', error);
}
});
4. 表单数据提交
$('#myForm').submit(function(e) {
e.preventDefault(); // 阻止表单默认提交行为
$.ajax({
url: $(this).attr('action'),
type: 'POST',
data: $(this).serialize(), // 序列化表单数据
dataType: 'json',
success: function(data) {
alert('表单提交成功!');
},
error: function(xhr, status, error) {
alert('表单提交失败: ' + error);
}
});
});
5. 文件上传
$('#fileUpload').change(function() {
var formData = new FormData();
formData.append('file', this.files[0]);
$.ajax({
url: '/api/upload',
type: 'POST',
data: formData,
processData: false, // 不处理数据
contentType: false, // 不设置内容类型
dataType: 'json',
success: function(data) {
console.log('文件上传成功:', data);
},
error: function(xhr, status, error) {
console.error('文件上传失败:', error);
},
xhr: function() {
// 获取原生XHR对象
var xhr = $.ajaxSettings.xhr();
if (xhr.upload) {
// 添加上传进度事件
xhr.upload.addEventListener('progress', function(e) {
if (e.lengthComputable) {
var percent = Math.round((e.loaded / e.total) * 100);
$('#progress').text(percent + '%');
}
}, false);
}
return xhr;
}
});
});
6. 简写方法
jQuery提供了一些Ajax的简写方法:
$.get();
$.get('/api/data', {id: 123}, function(data) {
console.log('获取数据:', data);
}, 'json');
$.post();
$.post('/api/users', {name: '李四', age: 30}, function(data) {
console.log('创建用户:', data);
}, 'json');
$.getJSON();
$.getJSON('/api/data.json', function(data) {
console.log('JSON数据:', data);
});
7. 全局Ajax设置
可以设置全局Ajax默认值:
$.ajaxSetup({
timeout: 5000, // 5秒超时
headers: { // 设置请求头
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
8. 使用Promise风格
jQuery Ajax也支持Promise风格调用:
$.ajax({
url: '/api/data',
type: 'GET',
dataType: 'json'
})
.done(function(data) {
console.log('成功:', data);
})
.fail(function(xhr, status, error) {
console.error('失败:', error);
})
.always(function() {
console.log('请求完成');
});