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

2021-12-18 00:00:00 jquery php laravel laravel-5 ajax

我正在尝试通过 ajax 向数据库提交数据.提交文章页面在没有 ajax 的情况下工作正常.我添加了 console.log() 只是为了看看是否有任何事情发生,但我收到了这个错误:

I'm trying to submit data to the database via ajax. The submit article page works fine without ajax. I've added console.log() just to see if anything is going through, but instead I'm getting this error:

POST http://localhost/laravel-5/public/articles/create500(内部服务器错误)

POST http://localhost/laravel-5/public/articles/create 500 (Internal Server Error)

我的代码有什么问题?是 javascript 还是控制器?

What's wrong with my code? Is it the javascript or the controller?

我在 laravel.log

C:xampphtdocslaravel-5vendorlaravelframeworksrcIlluminateFoundationHttpMiddlewareVerifyCsrfToken.php:53 中的异常 'IlluminateSessionTokenMismatchException'

exception 'IlluminateSessionTokenMismatchException' in C:xampphtdocslaravel-5vendorlaravelframeworksrcIlluminateFoundationHttpMiddlewareVerifyCsrfToken.php:53

路线

Route::resource('articles', 'ArticlesController');

控制器

public function store(RequestsArticleRequest $request)
    {

        $article = new Article($request->all());
        Auth::user()->articles()->save($article);

        $response = array(
            'status' => 'success',
            'msg' => 'Article has been posted.',
        );
        return Response::json($response);
    }

jQuery

$(document).ready(function() {
    $('#frm').on('submit', function (e) {
        e.preventDefault();
        var title = $('#title').val();
        var body = $('#body').val();
        var published_at = $('#published_at').val();
        $.ajax({
            type: "POST",
            url: 'http://localhost/laravel-5/public/articles/create',
            dataType: 'JSON',
            data: {title: title, body: body, published_at: published_at},
            success: function( data ) {
                $("#ajaxResponse").append(data.msg);
                console.log(data);
            }
        });
    });

查看

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">

<h1>Write a New Article</h1>

<hr>

{!! Form::open(['url' => 'articles', 'id' => 'frm']) !!}
    <p>
        {!! Form::label('title', 'Title:') !!}
        {!! Form::text('title') !!}
    </p>

    <p>
        {!! Form::label('body', 'Body:') !!}
        {!! Form::textarea('body') !!}
    </p>

    <p>
        {!! Form::label('published_at', 'Date:') !!}
        {!! Form::input('date', 'published_at', date('Y-m-d'), ['class' => 'form-control']) !!}
    </p>

    <p>
        {!! Form::submit('Submit Article', ['id' => 'submit']) !!}
    </p>
{!! Form::close() !!}

<h3 id="ajaxResponse"></h3>

@if($errors->any())
    <ul>
    @foreach($errors->all() as $error)
        <li>{{ $error }}</li>
    @endforeach
    </ul>
@endif

<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="{{ URL::asset('assets/js/ArticleCreate.js') }}"></script>

});

推荐答案

当你通过 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()
        }
});

相关文章