【问题标题】:Failed to load resource: the server responded with a status of 500 (Internal Server Error) in ajax with laravel加载资源失败:服务器在 ajax 中使用 laravel 响应状态为 500(内部服务器错误)
【发布时间】:2019-02-19 23:23:44
【问题描述】:

app.jss 文件

$('#modal-save').on('click', function(){

    // geting the properties
    $.ajax({
        method:'POST',
        url: url,
        data: {body: $('#post-body').val(), postId: postId , _token: token}
    })

    // after done
    .done(function(msg) {
        $(postBodyElement).text(msg['new_body']);
        $('#edit-modal').modal('hide')
    });
});

我在视图代码中的脚本

<script>
    var token = '{{ Session::token() }}';
    var url = '{{ route('edit') }}';
</script>

路线文件

Route::post('/edit', [
    'uses'=>'PostController@postEditPost',
    'as'=>'edit'
]);

我的控制器文件

public function postEditPost( Request $request)
{
    $this->validate($request,[
        'body' => 'required'
    ]);

    // checking auth user
    $post = Post::find($request['postId']);
    if(Auth::user != $post->user){
        return redirect()->back();
    }

    // updating the post content
    $post->body = $request['body'];
    $post->update();
    return response()->json(['new_body' => $post->body], 200);
}

【问题讨论】:

    标签: ajax laravel laravel-5


    【解决方案1】:

    您正在向服务器发送 ajax 请求,但不要像在控制器中那样接受它。 试试这个:

        // updating the post content
        $post->body = $request['body'];
        $post->update();
    
        if(request()->expectsJson()){
          return response()->json(['new_body' => $post->body], 200);
          }
    
         //here you can return to whereever you need it if its not ajax
        return redirect('/');
    

    【讨论】:

    • 不工作,实际上在我的脚本标签中我正在传递令牌 {{ Session::token() }} 但在 ajax 中找不到它.. 这就是问题
    • 我刚刚发现错误是因为 if(Auth::user != $post->user){ return redirect()->back(); }
    【解决方案2】:

    由于VerifyCsrfToken 中间件,您必须为每个post, put, delete 请求提供CSRF 令牌。

    head标签内添加元标签

    <meta name="csrf-token" content="{{ csrf_token() }}">
    

    然后在你的ajax请求中使用它

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

    X-CSRF-TOKEN

    【讨论】:

    • 先谢谢。我在隐藏输入中发送了 _token.. 有效果吗?.. 我也添加了这个但不起作用
    • 在 ajax 调用中,令牌应通过 http 标头作为X-CSRF-TOKEN 发送,因此您应该在任何调用之前执行$.ajaxSetup
    • 我发送了这样的令牌..我怎样才能在 $.ajax 设置中得到这个...
    • 错误是因为 if(Auth::user != $post->user){ return redirect()->back(); } 在控制器中
    • var url = '{{ route('edit') }}';更改为var url = '{{ url('edit') }}';
    猜你喜欢
    • 2015-12-19
    • 2013-04-16
    • 1970-01-01
    • 1970-01-01
    • 2018-01-22
    • 2014-11-24
    • 2021-07-27
    • 1970-01-01
    相关资源
    最近更新 更多