jQuery:AJAX
jQuery 包含一些 AJAX 辅助方法,可以节省时间并且更易于阅读。它们都是 $ 变量的属性:$.get、$.post 和 $.ajax。
$.ajax 是主要方法,允许您手动构建 AJAX 请求 - 其他方法是对常见配置的快捷方式,例如获取数据或发布数据。
这是一个从服务器获取数据的示例
$.ajax({
url: '/data.json',
method: 'GET',
success: function (data) {
console.log(data);
}
});
您可以看到使用了一个配置对象来告诉 jQuery 如何获取数据。提供了基本信息:URL、方法(实际上默认为 get)以及在数据检索时调用的函数,称为成功回调。
$.get
这个示例只是获取一些数据,因为这是一项非常常见的活动,jQuery 提供了一个辅助方法:$.get。
$.get('/data.json', function (data) {
console.log(data);
});
您还可以提供一个错误回调,它会在出现问题且无法连接到服务器时通知您
$.get('/data.json', function (data) {
console.log(data);
}).fail(function () {
// Uh oh, something went wrong
});
$.post
使用 $.post 方法发送数据到服务器也很容易。第二个参数是要发送的数据 - 它可以是除函数以外的几乎任何内容:jQuery 会为您处理如何发送它。多么方便!
$.post('/save', { username: 'tom' }, function (data) {
console.log(data);
}).fail(function () {
// Uh oh, something went wrong
});
$.ajax
当然,如果您想对数据发送方式有更多控制,请使用 $.ajax 手动设置请求。
$.ajax({
url: '/save',
method: 'POST',
data: { username: 'tom' },
success: function (data) {
console.log(data);
}),
error: function () {
// Uh oh, something went wrong
}
});
