在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"
我在这里需要一些帮助我被困住了
答案 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);
});
}
});