dqlb38410 2017-10-20 21:52
浏览 151
已采纳

AJAX POST请求不在后期路由中调用Controller方法

My code gives me 500 Internal Server error when trying to make AJAX POST request. I've done the CSRF Token part.

This is my JS code

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

$('#likeBtn').on('click', function(e){

    e.preventDefault();

    //Getting urlLink and activityId - works

    $.ajax({
        type: 'POST',
        url: './mainView/postlike',
        data: {activityId : activityId},
        success: function(data){
            console.log(JSON.stringify(data));
        },
        error: function(e){
            console.log(JSON.stringify("Exception: " + e));
        }
    });
});

This is my post Route :

Route::post('/mainView/postlike', 'ActivityController@postLike')->name('postLike')->middleware('auth');

This is my controller method :

public function postLike(){
    if(Request::ajax()){
        return Response::json(Request::all());
    }
}

This is my mainView.blade.php. I didn't really want to use a form but I tried anyway.

<form id="likeForm" method="POST" action="#">
    <input class="likeToken" type="hidden" name="_token" value="{{ csrf_token() }}">
    <a id="likeBtn" data="{{ route('activity.like', ['activityId' => $activity->activity_id]) }}">
    <img src="IMG/icons/like.png" alt="likes">
    </a>{{ $activity->likes->count() }}
</form>

That being said, if I do this in my route, it outputs the message provided.

Route::post('/mainView/postlike', function(){
    if(Request::ajax()){
        echo "Hi";
    }
})->name('postLike')->middleware('auth');

It shows "Hi" when the like button is pressed

  • 写回答

1条回答 默认 最新

  • dongmou3615 2017-10-20 22:00
    关注

    In the comments, you've posted the error message. To fix it, change this:

    if(Request::ajax()){
    

    to this:

    if (request()->ajax()) {
    

    For the second error:

    response()->json(request()->all());
    

    Also, you can inject Request class:

    public function postLike(Request $request)
    

    And use $request instead of request()

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料