在论坛上查看同一问题的不同问题后,我仍然不知道如何解决我的请求方法'DELETE'不支持
当客户端中的用户按下按钮时会触发Ajax方法调用,此方法检索包含在Ajax调用中的 sportId 并发送给spring控制器删除方法。
Ajax方法:
function removeRow(link) {
var sportId = link.getAttribute("data-sport-id");
$.ajax({
type : "DELETE",
url : "/sports-actions",
data: {id : sportId},
contentType: "application/json",
dataType : 'json',
success: function (result) {
console.log(result);
},
error: function (e) {
console.log(e);
}
})
}
Spring控制器:
@RestController
@RequestMapping("/sports-actions")
public class SportController {
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
public Object deleteSport(@PathVariable("id") String id) {
return null;
}
}
修改
即使我在网址中发送了ID,我仍然会收到相同的错误
Ajax代码:
$.ajax({
type : 'DELETE',
contentType: "application/json",
url : "/sports-actions?id="+sportId,
dataType : 'json',
success: function (result) {
console.log(result);
},
error: function (e) {
console.log(e);
}
})
答案 0 :(得分:2)
您正在向不正确的网址发送请求。您将控制器的路径声明为/sports-actions/{id}
,但实际上将其发送到带有json正文的/sports-actions
。
正确的代码:
$.ajax({
type : "DELETE",
url : "/sports-actions/" + sportId,
success: function (result) {
console.log(result);
},
error: function (e) {
console.log(e);
}
});
答案 1 :(得分:2)
请查看@RequestParam
和@PathVariable
之间的区别。
如果您想使用@ReqeustParam
:
$.ajax({
type : "DELETE",
url : "/sports-actions",
data: {"id" : sportId},
contentType: "application/json",
dataType : 'json',
success: function (result) {
console.log(result);
},
error: function (e) {
console.log(e);
}
})
@RestController
@RequestMapping("/sports-actions")
public class SportController {
@RequestMapping(method = RequestMethod.DELETE)
public Object deleteSport(@RequestParam("id") String id) {
return null;
}
}
如果您想使用@PathVariable
$.ajax({
type : "DELETE",
url : "/sports-actions/" + sportId,
contentType: "application/json",
dataType : 'json',
success: function (result) {
console.log(result);
},
error: function (e) {
console.log(e);
}
})
@RestController
@RequestMapping("/sports-actions")
public class SportController {
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
public Object deleteSport(@PathVariable("id") String id) {
return null;
}
}
PS :遵循Restful
最佳做法总是好的。 see here