jquery中发送ajax请求中method和type的区别
时间: 2024-05-04 08:16:55 浏览: 7
在jQuery中发送Ajax请求时,`method`和`type`参数都可以设置请求的HTTP方法,但是`type`参数已经在jQuery 1.9版本中被废弃,推荐使用`method`参数。
在jQuery 1.9版本之前,`type`参数是用来设置请求的HTTP方法的,如`GET`、`POST`、`PUT`、`DELETE`等。而`method`参数是用来设置请求类型的,如`text`、`html`、`xml`、`json`等。
但是,`type`参数的命名与jQuery中的其他方法和属性(如`.attr()`和`.prop()`)的命名不一致,因此在1.9版本中被废弃。
因此,在现在的jQuery版本中,我们应该使用`method`参数来设置请求的HTTP方法,如下所示:
```javascript
$.ajax({
url: 'example.php',
method: 'POST',
data: { name: 'John', age: 30 },
success: function(response) {
console.log(response);
}
});
```
其中,`method`参数可以设置为`GET`、`POST`、`PUT`、`DELETE`等HTTP方法。
相关问题
用jquery的ajax请求报错405 Method Not Allowed
当使用jQuery的ajax请求时,出现405 Method Not Allowed错误通常是由于请求方法不正确导致的。这个错误通常发生在使用POST请求时,但服务器只允许GET请求。解决这个问题的方法是确保请求方法与服务器允许的方法相匹配。以下是一些可能有用的解决方法:
1. 确保请求的URL正确,包括协议、主机名、端口和路径。
2. 确保请求的方法与服务器允许的方法相匹配。可以通过在ajax请求中设置type属性来指定请求方法,例如:
```javascript
$.ajax({
type: "POST",
url: "http://localhost:1405/api/login/valid",
data: JSON.stringify(param),
contentType: "application/json",
dataType: "json",
success: function(res) {
alert(res);
},
error: function() {
alert("登录失败!");
}
});
```
3. 确保服务器允许跨域请求。如果您的ajax请求是跨域的,您需要在服务器端配置CORS(跨域资源共享)以允许跨域请求。您可以在服务器端设置响应头来允许跨域请求,例如:
```javascript
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: POST, GET, OPTIONS
Access-Control-Allow-Headers: Content-Type
```
jQuery发送get请求和post请求
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()方法将其转换为字符串格式。