简体   繁体   English

laravel AJAX发布

[英]laravel AJAX post

I am trying to learn using AJAX with laravel, my knowledge of AJAX is practically zero. 我正在尝试将Laravel与AJAX结合使用,我对AJAX的了解几乎为零。 The last few days I tried to solve this. 最近几天,我试图解决这个问题。 But I can't get it to work... 但是我无法正常工作...

Basically when a user clicks the like button of a post, I want to submit that request to my LikeController. 基本上,当用户单击帖子的“赞”按钮时,我想将该请求提交给我的LikeController。 The LikeController works so that can't be the issue, it seems that no data is passed by AJAX to the Controller. LikeController可以正常工作,因此不会出现问题,似乎AJAX不会将任何数据传递给Controller。 Can someone point out what I am doing wrong? 有人可以指出我做错了吗?

My route: 我的路线:

Route::post('posts/like', [
    'as' => 'posts.like', 
    'uses' => 'LikeController@likePost'
]); 

My controller: 我的控制器:

public function likePost(Request $request)
    {
        // Validation
        $this->handleLike('App\Post', $request['postId']);
        return response()->json(['msg' => 'success'], 200);
    }

    public function handleLike($type, $postId)
    {
        $existing_like = Like::withTrashed()->whereLikeableType($type)->whereLikeableId($postId)->whereUserId(Auth::id())->first();

        if (is_null($existing_like)) {
            Like::create([
                'user_id'       => Auth::id(),
                'likeable_id'   => $postId,
                'likeable_type' => $type,
            ]);
        } else {
            if (is_null($existing_like->deleted_at)) {
                $existing_like->delete();
            } else {
                $existing_like->restore();
            }
        }
    }

And the JS: 和JS:

$('.like').on('click', function(event) {
    event.preventDefault();

    postId = event.target.dataset['postid'];

    console.log(postId)
    console.log(token) 

    $.ajax({
        method: 'POST',
        url: urlLike,  // Gets defined in the view
        data: {postId: postId, _token: token}
    }).done(function(msg) {
           console.log(msg); // never even reached this stage...
    });
});

What output do you get in the console? 您在控制台中得到什么输出? error 500? 错误500?

For ajax to work, you need to send the csrf token with your request. 为了使ajax正常工作,您需要将csrf令牌与请求一起发送。

https://laravel.com/docs/master/routing#csrf-x-csrf-token https://laravel.com/docs/master/routing#csrf-x-csrf-token

To properly debug ajax request i recommend you to use artisan tail, this helps you to watch error messages when working with ajax. 为了正确调试ajax请求,我建议您使用artisan tail,这可以帮助您在使用ajax时观看错误消息。

https://github.com/spatie/laravel-tail https://github.com/spatie/laravel-tail

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM