Laravel和AJAX 401未经授权

时间:2018-05-13 20:11:23

标签: ajax laravel laravel-5

如何获取我的代码,以便如果我的AJAX按钮点击代码出现401错误,那么当点击按钮时它会抛出一条错误消息并说“你需要登录"或者它将用户重定向到登录?目前它只是在开发控制台中抛出错误,因此用户不知道为什么按钮不起作用。

Ajax js:

$('.visit').on('click', function (event) {
event.preventDefault();
// Make the button a variable here
var buttonToChange = $(this);
$.ajax({
    method: 'POST',
    url: urlVisit,
    data: {
        place_id: $(event.target).data("id"),
        _token: token
    },
    success: function(){
    // Change the button here
        if(buttonToChange.hasClass('btn-visited')){
            buttonToChange.addClass('btn-not-visited');
            buttonToChange.removeClass('btn-visited');
            buttonToChange.html('Not Visited');
        //Count will go down
        }
        else{
            // Do the opposite
            buttonToChange.addClass('btn-visited');
            buttonToChange.removeClass('btn-not-visited');
            buttonToChange.html('Visited');
//count will go up
        }
    },
});

2 个答案:

答案 0 :(得分:0)

简单示例

您可以在浏览器中通过inspect测试此代码:

welcome.blade.php

    <script>
        var urlVisit="{{route('route_test')}}"
        var token = "{{csrf_token()}}"
        $.ajax({
            method: 'POST',
            url: urlVisit,
            data: {
                place_id: 1,
                _token: token
            },
            success: function (response) {
                alert('ok')

            },
            error: function (xhr, ajaxOptions, thrownError) {
                if (xhr.status == 419)
                {
                    alert(xhr.responseText) // text of error

                    // do something
                }
                else if(xhr.status == 401)
                {
                    // do something
                }

            }

        });
    </script>

web.php(路线):

use Illuminate\Http\Request;
Route::get('/', function () {
    return view('welcome');
});

Route::post('test', function (Request $request) {
    $place_id= $request->get('place_id');
    return ('yes');
})->name('route_test');

答案 1 :(得分:0)

您可以尝试jQuery AJAX的statusCode部分。

$('.visit').on('click', function (event) {
event.preventDefault();
// Make the button a variable here
var buttonToChange = $(this);
$.ajax({
    method: 'POST',
    url: urlVisit,
    data: {
        place_id: $(event.target).data("id"),
        _token: token
    },
    statusCode: {
        401: function() {
            alert( "Not authenticated" );
        }
    }
success: function(){
// Change the button here
    if(buttonToChange.hasClass('btn-visited')){
        buttonToChange.addClass('btn-not-visited');
        buttonToChange.removeClass('btn-visited');
        buttonToChange.html('Not Visited');
    //Count will go down
    }
    else{
        // Do the opposite
        buttonToChange.addClass('btn-visited');
        buttonToChange.removeClass('btn-not-visited');
        buttonToChange.html('Visited');
//count will go up
    }
},
});