【问题标题】:How to delete record in laravel 5.3 using ajax request?如何使用 ajax 请求删除 laravel 5.3 中的记录?
【发布时间】:2017-01-14 00:34:50
【问题描述】:

我正在尝试在 laravel 5.3 中使用 ajax 删除记录,我知道这是常见问题之一,并且已经有很多关于此主题的在线解决方案和教程。我尝试了其中一些,但大多数都给了我同样的错误NetworkError: 405 Method Not Allowed。我试图从不同的角度完成这项任务,但我被卡住了,找不到我错的地方,这就是为什么我添加了这个问题作为指导。

我正在尝试使用以下脚本来删除记录。

Controller.php

public function destroy($id)
{   //For Deleting Users
    $Users = new UserModel;
    $Users = UserModel::find($id);
    $Users->delete($id);
    return response()->json([
        'success' => 'Record has been deleted successfully!'
    ]);
}

Routes.php

Route::get('/user/delete/{id}', 'UserController@destroy');

可见

<button class="deleteProduct" data-id="{{ $user->id }}" data-token="{{ csrf_token() }}" >Delete Task</button>

App.js

$(".deleteProduct").click(function(){
        var id = $(this).data("id");
        var token = $(this).data("token");
        $.ajax(
        {
            url: "user/delete/"+id,
            type: 'PUT',
            dataType: "JSON",
            data: {
                "id": id,
                "_method": 'DELETE',
                "_token": token,
            },
            success: function ()
            {
                console.log("it Work");
            }
        });

        console.log("It failed");
    });

当我单击删除按钮时,它在控制台中返回错误NetworkError: 405 Method Not Allowed。没有 ajax 相同的删除功能可以正常工作。

谁能指导我哪里我错了,我可以解决这个问题,如果有人指导我解决这个问题,我将不胜感激。谢谢你。。

【问题讨论】:

    标签: php ajax laravel laravel-5


    【解决方案1】:

    不要使用Route::get,而是使用Route::delete

    除此之外,将 ajax 调用中的 type: 'Put' 更改为 type: 'DELETE'


    附:这段代码

    $Users = new UserModel;        // Totally useless line
    $Users = UserModel::find($id); // Can chain this line with the next one
    $Users->delete($id);
    

    可以写成:

    UserModel::find($id)->delete();
    

    甚至更短:

    UserModel::destroy($id);
    

    请记住,-&gt;delete() 会触发事件,而::destroy() 不会。

    【讨论】:

    • 感谢您的指导,我按照您的指示进行操作,但仍然面临同样的问题。
    • 你试过在你的ajax调用中使用type: 'DELETE'吗?
    • 让我检查一下
    • 哇,完美,现在可以使用了。非常感谢您的指导 +1
    【解决方案2】:

    确保将其添加到视图的 meta 标记中

        <meta name="csrf-token" content="{{ csrf_token() }}">
    

    在您的Routes 中,执行此操作

    Route::delete('/user/delete/{id}', 'UserController@destroy');
    

    在您的控制器中,执行此操作

    UserModel::destroy($id);
    

    DB::table('table_name')->where('id', $id)->delete();
    

    确保检查删除帐户的用户是否确实拥有该帐户,也就是运行授权测试。

    由于这是一个delete 请求,因此您需要按照官方网站的说明发送csrf_token 以及您的ajax 标头。 https://laravel.com/docs/5.5/csrf#csrf-x-csrf-token

    确保在ajax调用之前添加这个

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

    现在发送请求

    $(".deleteProduct").click(function(){
        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });
        $.ajax(
        {
            url: "user/delete/"+id,
            type: 'delete', // replaced from put
            dataType: "JSON",
            data: {
                "id": id // method and token not needed in data
            },
            success: function (response)
            {
                console.log(response); // see the reponse sent
            },
            error: function(xhr) {
             console.log(xhr.responseText); // this line will save you tons of hours while debugging
            // do something here because of error
           }
        });
    });
    

    我希望这会有所帮助。

    【讨论】:

      【解决方案3】:
      $(".deleteProduct").click(function(){
      $.ajaxSetup({
          headers: {
              'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
          }
      });
      $.ajax(
      {
          url: "user/delete/"+id,
          type: 'DELETE', // Just delete Latter Capital Is Working Fine
          dataType: "JSON",
          data: {
              "id": id // method and token not needed in data
          },
          success: function (response)
          {
              console.log(response); // see the reponse sent
          },
          error: function(xhr) {
           console.log(xhr.responseText); // this line will save you tons of hours while debugging
          // do something here because of error
         }
      });
      

      });

      【讨论】:

        【解决方案4】:

        我正在使用请求动词恢复删除工作流程。希望对你有帮助

        并且控制器中有一个注释代码可以处理 ajax 请求

        形式(带刀片):

          {{ Form::open(['method' => 'DELETE', 'route' => ['admin.products.edit', $product->id], 'name' => 'delete']) }}
            {{ Form::close() }}
        

        路线:

        Route::delete('admin/products/{id}/edit', ['as' => 'admin.products.edit', 'uses' => 'Product\ProductController@delete']);
        

        产品控制器:

         public function delete($id)
            {
                // if (Request::ajax()) {
                // if (Request::isMethod('delete')){
        
                $item = Product::findOrFail($id);
                $item->delete();
        
                return redirect()->route('admin.products')->with('flashSuccess', 'deleted');
            }
        

        在重定向部分,我将返回我的列表页面 (admin.products) 并显示成功通知。路线是:

        Route::get('admin/products', ['as' => 'admin.products', 'uses' => 'Product\ProductController@getList']);
        

        这样你就可以完成流程了。

        【讨论】:

          猜你喜欢
          • 2017-02-19
          • 2016-12-01
          • 1970-01-01
          • 2010-11-18
          • 1970-01-01
          • 2019-04-12
          • 2017-06-11
          • 1970-01-01
          • 2013-10-27
          相关资源
          最近更新 更多