错误405(不允许PUT方法)使用Ajax的Laravel 5.4资源

时间:2018-03-16 18:14:36

标签: jquery ajax laravel laravel-5 laravel-routing

在routes.php中:

Route::resource('/users','UserController');

ajax.js:

 $.ajax({
            url: "/users",
            type:'POST',
            data:$('.edit-user-form').serialize(),
            success: function(data) {
                console.log('success');
                console.log(data);
            },
            error: function(data){
                console.log('error');
                console.log(data);
                });
            }
        });

blade.php:

<form class="edit-user-form" action="/users" method="POST">
     {{ method_field('PUT') }}
     {{csrf_field()}}
.......my inputs here .....
</form>

Controller.php:

 public function store(Request $request)
{
    return response()->json(['response' => 'This is POST method']);
}
  public function update(Request $request, $id)
{
    return response()->json(['response' => 'This is PUT method']);
}

在POST方法中,它显示在控制台中:

success
Object { response: "This is POST method" }

当我将{{ method_field('PUT') }}添加到我在控制台中显示的form时:

error
status: 405
statusText: "Method Not Allowed"

我在这里需要一些帮助我被困住了

2 个答案:

答案 0 :(得分:0)

由于您正在使用资源路线。请将ajax请求类型更改为PATCH

$.ajax({
        url: "/users",
        type:'PATCH',
       ......
        });

同样在表单方法中,将POST更改为PATCH

<form class="edit-user-form" action="/users" method="PATCH">
     {{csrf_field()}}
.......my inputs here .....
</form>

选中Laravel文档

答案 1 :(得分:0)

我认为您使用了错误的操作网址。将其更改为

<form class="edit-user-form" action="{{route('users.update',$user->id)}}" method="post">
 {{csrf_field()}}
 {{method_field('PUT')}}
.......my inputs here .....
</form>


$.ajax({
        url: '{{route('users.update',$user->id)}}',
        type:'POST',
        data:$('.edit-user-form').serialize(),
        success: function(data) {
            console.log('success');
            console.log(data);
        },
        error: function(data){
            console.log('error');
            console.log(data);
            });
        }
    });