weixin_33691817 2019-04-14 20:26 采纳率: 0%
浏览 13

Laravel Ajax帖子调用失败

I found several solutions to this one, tried them all (csrf tokens, urls..) but none of them seems to work.

This is my setup:

html file:

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

...

    <button id="button" class="btn btn-success">Assign Selected</button>

...

My js file:

$(document).ready(function () {

 $('#button').click(function (e) {


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

        $.ajax({
                type: "POST",
                dataType: 'json',
                url: '/wptest',
                data: { data: 'ahoj' }
            }).done(function (data) {
                console.log('Ajax was Successful!')
                console.log(data)
            }).fail(function () {
                console.log('Ajax Failed')
            });
    });

}

And my web.php file:

Route::post('/wptest','UserController@assignToWP');

In my controller there is just a simple dd($request);

Edit: network tab shows: 200 OK

Problem: I always get Ajax Failed after button click. What do I miss?

  • 写回答

1条回答 默认 最新

  • 七度&光 2019-04-14 20:38
    关注

    Ok I found the solution:

    The whole problem is, that in order for ajax to be successful, the controller needs to pass and return. dd function kills the controller before return and ajax fail therefore.

    Make sure controller always gets to its return line.

    评论

报告相同问题?