在 html 中有一个按钮,因此当您单击它时,它会向.post
jQuery 请求发送到必须处理请求然后返回成功 json 的控制器,但我收到一个错误(注意错误是 console.log(数据)):
jquery.min.js:2 POST http://127.0.0.1:8000/comment/like 500(内部服务器错误)
在控制台中。当我进一步查看时,Laravel 应用程序返回此错误:
此路由不支持 GET 方法。支持的方法:POST、PUT、DELETE。
使用此 json 响应文本:
#json: null
#convertedFiles: null
#userResolver: Closure($guard = null) {#197 …6}
#routeResolver: null
+attributes: ParameterBag {#45}
+request: ParameterBag {#51}
+query: ParameterBag {#51}
+server: ServerBag {#47}
+files: FileBag {#48}
+cookies: ParameterBag {#46}
+headers: HeaderBag {#49}
#content: null
#languages: null
#charsets: null
#encodings: null
#acceptableContentTypes: array:6 [▶]
#pathInfo: "/comment/like"
#requestUri: "/comment/like"
#baseUrl: ""
#basePath: null
#method: "GET"
#format: null
#session: null
#locale: null
#defaultLocale: "en"
-isHostValid: true
-isForwardedValid: true
basePath: ""
format: "html"
所以我知道它必须是 POST 路由,但 web.php 控制器中的路由是这样的
Route::post('/comment/like','LikeController@likeIt')->name('likeIt');
当我对 500 服务器错误进行一些研究时,我得到了大多数需要添加的答案,csrfToken
但我csrfToken
在 jQuery ajax 请求中有,所以我不明白为什么它说它不是发布请求而是获取请求?
控制器
public function likeIt()
{
$commentId = Input::get('commentId');
$comment = Comment::find($commentId);
$comment->likeIt();
return response()->json(['status' => 'succes']);
}
html
<button class="btn btn-sm" id="{{$comment->id}}" onclick="likeIt('{{$comment->id}}', this)"><i class="material-icons">done</i></button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function likeIt(commentId, elem) {
const csrfToken='{{csrf_token()}}';
$.post('{{route('likeIt')}}', {commentId:
commentId,_token:csrfToken}, function (data) {
console.log(data);
});
}
</script>