dongtui0650 2018-01-16 06:37
浏览 189
已采纳

Laravel Delete按钮无法使用Ajax调用

I have a Laravel post application where I create and display posts. I am now trying to delete a post using an Ajax call. Let's say I have 10 posts displaying. When I click on the delete button of the first post, I get a 405 Method Not Allowed error. When I click on the delete button on any of the posts below, absolutely nothing happens, no error or warning message. Please take note that my CSRF tokens are set up and working. Any help or suggestions will be appreciated.

Here is the HTML:

    @foreach($posts as $post)
    <div class="postContainer" id="post{{ $post->id }}">
      <h4 class="postHeading" id="showtitle">{{ $post->title }}</h4>
      <p class="post" id="postBody">{{ $post->post }}</p>
      <span class="authorName" id="showauthor">{{ $post->author }}</span>
      <span class="postDate" id="showpostDate">{{ $post->created_at }}</span>
      <input type="submit" name="delete" id="delete" value="Delete" data-id="{{ $post->id }}">
    </div>
    @endforeach
    <div class="message" id="message">

    </div>

Here is my Ajax call:

    $("#delete").on("click", function(){

      var id = $(this).attr('data-id');

      $.ajaxSetup({
        headers: {
          'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr("content")
        }
      });

      $.ajax({
        url: '/index/delete/' + id,
        type: "POST",
        data: {_method: 'delete'},
        success:function(response){
          $("#message").append("<div>" + response.message + "</div>");
        },
      });

    });

Here is my Route:

   Route::post('/index/delete/{id}', 'HomeController@delete');

Here is my controller:

public function delete($id){
  Post::find($id)->delete();
  return redirect('/');
}
  • 写回答

2条回答 默认 最新

  • dongyi1159 2018-01-16 06:40
    关注

    Change this in your code

    id to class

    <input type="submit" name="delete" class="delete" value="Delete" data-id="{{ $post->id }}">
    

    in script

    call class(.) not id(#)

    and data('id') not attr('data-id')

    $(".delete").on("click", function(){
        var id = $(this).data('id');
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵