且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Laravel 5:Ajax Post 500(内部服务器错误)

更新时间:2021-11-26 01:03:59

当你通过 POST 向资源控制器发出请求时,它会自动调用 store 方法:

When you make a request via POST to a resource controller, it automatically calls store method:

Verb    Path        Action  Route Name
----------------------------------
POST    /articles   store   articles.store

所以,你只需要把ajax url改成:

So, you just need to change ajax url to:

$.ajax({
        type: "POST",
        url: 'http://localhost/laravel-5/public/articles',

当您需要发送会话令牌时,您可以添加一个全局元标记,例如您的网站:

When you need to send the session token, you can add a global meta-tag like this is you website:

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

然后,只需通过ajax的标题添加令牌:

Then, just add the token via ajax's headers:

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

如果您使用 Form::open() 函数 (LaravelCollective),它会添加一个隐藏输入,其中包含名称为 _token 的令牌作为值.因此,您可以删除元标记并像这样编辑 ajax 的标题:

If you are using Form::open() function (LaravelCollective) it adds a hidden input with the token as value with the name _token. So, you can remove the meta-tag and edit your ajax's headers like this:

$.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('[name="_token"]').val()
        }
});