如何修复Spring Boot Controller从AJAX DELETE请求获取空数据?

时间:2019-03-26 01:03:07

标签: java ajax spring-boot spring-boot-maven-plugin

我尝试使用@ QueryParam,@ PathVariable和@RequestParam,但我的控制器未从AJAX调用获取数据请求。我的其他方法也一样。只有DELETE请求无法正常工作,并且我得到的是空值。我已经提到了这个Ajax delete method in spring boot,但它对我没有用。

//AJAX DELETE
var id = {"id":$("#deleteUserIdInput").val()};

$("#deleteUserModal").modal("hide");

$.ajax({
    url : "http://localhost:3000/delete-user",
    datatype : "json",
    method : "DELETE",
    data : id,
    contentType : "application/json",
    error:function(data){
        console.log(data.entity);
    }
}).done(function(data) {
        console.log(data.entity)
    }
);

//Controller
//http://localhost:3000/delete-user
@RequestMapping(value="/delete-user", method = RequestMethod.DELETE)
@ResponseBody
public Integer deleteUser(@QueryParam("id") Integer id){
    return id;
}

我在传递给请求之前正在测试数据,它不为null。我希望传递给请求的数据会返回,例如1,但是我变得不确定。

2 个答案:

答案 0 :(得分:1)

您似乎正在发送ID作为请求的正文。这意味着您需要让deleteUser方法将正文作为参数来接收。

我建议您从特定的网址(即http://localhost:3000/users/ {id}

中删除)

相应的方法声明变为:

@DeleteMapping("/users/{id}")
@ResponseBody
public Integer deleteUser(@PathVariable("id") Integer id){
    return id;
}

您的JS将需要修改(我认为-我不太擅长JS),例如(再次-我不是JS家伙,如果这很糟糕,对不起!):

$.ajax({
    url : "http://localhost:3000/users/" + $("#deleteUserIdInput").val(),
    datatype : "json",
    method : "DELETE",
    contentType : "application/json",
    error:function(data){
        console.log(data.entity);
    }
}).done(function(data) {
        console.log(data.entity)
    }
);

答案 1 :(得分:0)

我认为,您无法获得价值,可能是虚假的心。 您可以配置cors吗?

第一个请求可以获取删除请求的值,实际上删除请求是cors虚拟请求,ajax确认您的服务器正常,ajax可以发送agin。

您可以更改发布要求,而在服务器中更改发布以接收您的要求。