0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

やりたいこと

SNSのようなアプリケーションでユーザーが投稿からコメント削除をした場合に、ajaxでページ遷移や更新を行わず非同期で反映させたい

Thymeleafの記述

  • metaタグにCSRF対策トークン埋め込み
    • Spring Security使用している場合は設定しないと動かない
<meta name="_csrf" th:content="${_csrf.token}"/>
<meta name="_csrf_header" th:content="${_csrf.headerName}"/>
  • 必要なjsファイルとjQuery読み込み
<script th:src="@{/webjars/jquery/3.4.1/jquery.min.js}"></script>
<script th:src="@{/js/sample.js}"></script>

コメント一覧表示部分

show.html
  <th:block th:each="comment : ${todo.comments}">
    <div class="card my-3 w-50" th:data-id="${comment.id}">
      <div class="card-body">
        <p th:text="${comment.comment}"></p>
        <div class="d-grid gap-2 d-md-flex justify-content-md-end">
          <p class="my-auto" th:text="${#dates.format(comment.updatedDate,'yyyy/MM/dd HH:mm')}"></p>
          <button type="button" class="btn btn-outline-primary edit-comment" th:data-comment="${comment.comment}" th:data-id="${comment.id}" th:data-todo="${todo.id}" data-bs-toggle="modal" data-bs-target="#commentEditModal">Edit</button>
          <button type="button" class="btn btn-secondary delete-comment" th:data-id="${comment.id}">Delete</button>
        </div>
      </div>
    </div>
  </th:block>

ajax処理記述

resources/static/js/comment-delete.js
$(function (){
    // CSRF tokenをリクエストヘッダにセット
    let token = $("meta[name='_csrf']").attr("content");
    let header = $("meta[name='_csrf_header']").attr("content");
    $(document).ajaxSend(function(e, xhr, options) {
        xhr.setRequestHeader(header, token);
    });
    // コメント削除ボタンを押した場合の処理
    $('.delete-comment').on('click', function(e){
        // idの取得
        const commentId = $(e.currentTarget).data('id');
        // POSTでjson形式のデータを送信
        $.ajax({
            url: '/comment/delete',
            method: 'POST',
            data: {
                'commentId' : commentId,
            },
            dataType: 'json',
            // 削除に成功したら画面からもコメント削除
            success: function(data){
                $('.card[data-id="'+data+'"]').remove();
            },
            error: function(){ alert("コメントの削除に失敗しました"); },
        })
    });
}); 

Controller

CommentController.java
@RequestMapping(value = "/comment/delete",method = RequestMethod.POST)
@ResponseBody
public Long delete(@RequestParam("commentId") Long commentId){
    commentService.deleteComment(commentId);
    return commentId;
}
  • POSTcommentId削除対象のコメントID受け取り
  • @ResponseBodyで削除したcommentIdをjsonで返却
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?