gpt4 book ai didi

jquery - spring boot中ajax删除方法

转载 作者:行者123 更新时间:2023-12-01 06:43:44 25 4
gpt4 key购买 nike

在论坛上查看讨论同一问题的不同问题后,我仍然不知道如何解决我的不支持请求方法“DELETE”

客户端中的用户按下按钮时,会触发 Ajax 方法调用,此方法会检索 Ajax 调用中包含的 sportId 并将其发送到 Spring Controller 删除方法。

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 Controller :

@RestController
@RequestMapping("/sports-actions")
public class SportController {

@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
public Object deleteSport(@PathVariable("id") String id) {
return null;
}
}

编辑:

即使我在 url 中发送 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);
}
})

最佳答案

请查看@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

关于jquery - spring boot中ajax删除方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45018581/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com