jquery发送ajax请求
时间: 2023-09-21 12:10:12 浏览: 45
jQuery 发送 Ajax 请求有多种方式,下面是其中两种最常见且简单的方式:
1. 使用 `$.ajax()` 方法发送 Ajax 请求:
```javascript
$.ajax({
url: 'http://example.com/api/data',
method: 'GET',
data: { id: 123 },
dataType: 'json',
success: function(data) {
console.log(data);
},
error: function(xhr, status, error) {
console.error(error);
}
});
```
2. 使用 `$.get()` 或 `$.post()` 方法发送 Ajax 请求:
```javascript
$.get('http://example.com/api/data', { id: 123 }, function(data) {
console.log(data);
}, 'json');
$.post('http://example.com/api/data', { id: 123 }, function(data) {
console.log(data);
}, 'json');
```
以上代码分别使用了 `$.ajax()`、`$.get()` 和 `$.post()` 方法发送 GET 和 POST 请求,传递的参数分别包括请求 URL、请求参数、回调函数以及期望的响应数据类型。在回调函数中可以对响应数据进行处理,如打印到控制台或更新页面内容。如果请求出错,也可以在回调函数中处理错误信息。