簡體   English   中英

刪除請求的控制器不起作用

[英]Controller for delete request does not work

我的小型應用程序確實開始使用控制器,現在我有了這個:

@RequestMapping("/users/{id}")
public ModelAndView showMemeber(@PathVariable Integer id) {

    ModelAndView mav = new ModelAndView("user/show");

    mav.addObject("title", "Show User");
    mav.addObject("user", userService.findById(id));
    return mav;

}

@RequestMapping(value="/users/{id}", method=RequestMethod.DELETE)
public String deleteMemeber(@PathVariable Integer id) {

    userService.delete(id);

    return "redirect:users";

}

第一個,它工作正常,但是第二個沒有,我對第一個控制器有以下看法:

<div class="panel-heading">Personal information</div>
<div class="panel-body">

  <form>

    ...

    <button type="submit" class="btn btn-danger" onclick="return confirm('Are you sure you want to delete {{ user.username }}?')"><span class="glyphicon glyphicon-remove"></span> Delete</button>
  </form> 
</div>

如您所見,我在這里有兩個按鈕,一個用於編輯對象,一個用於刪除對象。 刪除后,必須重定向到https://<my domain>/users

問題是,當我單擊“ Delete ,僅刷新頁面,並且對象保留在數據庫中,這是什么問題?

  • 我嘗試發送像curl -X "DELETE" http://localhost:8080/my-app/users/18這樣的DELETE請求,但這沒有用。
  • 我嘗試使用jQuery的ajax方法的另一種方法 (但仍然存在相同的錯誤):

     $.ajax({ url: '/users/' + someUserId, type: 'DELETE', success: function(result) { // Do something with the result } }); 

您必須使用ajax從網頁發送DELETE。 表單標簽本身僅支持POST或GET。 在您的Submit-Handler中,您必須取消Submit按鈕的默認行為,即通過GET或POST( event.preventDefault() )提交表單:

$("form").submit(function (event) {
        event.preventDefault();

        $.ajax({
                url: '/users/' + someUserId,
                type: 'DELETE',
                success: function(result) {
                        // Do something with the result
                }
        });
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM