jQuery发送get请求和post请求
时间: 2023-07-01 17:21:07 浏览: 140
jQuery发送GET请求的方法:
```javascript
$.ajax({
url: "your_url",
method: "GET",
data: {key1: value1, key2: value2},
success: function(response) {
console.log(response);
},
error: function(error) {
console.log(error);
}
});
```
其中,url为请求的地址,method为请求的方法,data为请求的数据,success为请求成功后的回调函数,error为请求失败后的回调函数。
jQuery发送POST请求的方法:
```javascript
$.ajax({
url: "your_url",
method: "POST",
data: {key1: value1, key2: value2},
success: function(response) {
console.log(response);
},
error: function(error) {
console.log(error);
}
});
```
其中,url、method、success和error的含义与GET请求相同,data为请求的数据,需要注意的是,POST请求需要设置contentType为"application/x-www-form-urlencoded"或者"multipart/form-data"或者"application/json",具体的设置方法如下:
```javascript
$.ajax({
url: "your_url",
method: "POST",
contentType: "application/json",
data: JSON.stringify({key1: value1, key2: value2}),
success: function(response) {
console.log(response);
},
error: function(error) {
console.log(error);
}
});
```
其中,contentType为请求头中的"Content-Type"属性,需要根据实际情况设置。如果data是JSON格式的数据,需要使用JSON.stringify()方法将其转换为字符串格式。
阅读全文
相关推荐


















