简体   繁体   English

laravel 无法使用 ajax 服务器状态 419 发布数据

[英]laravel cannot post data with ajax server status 419

I am doing a project with Laravel.我正在用 Laravel 做一个项目。

When I change the selected option of the following select element I should insert the selected value to mysql database to retrieve all the data about the selected id from the server (for example the name of the user).当我更改以下 select 元素的选定选项时,我应该将选定的值插入 mysql 数据库,以从服务器检索有关选定 id 的所有数据(例如用户名)。

This is the select element (adminArea.blade.php):这是 select 元素 (adminArea.blade.php):

<select name="employees" onchange="fillEmployeeData(this)" class="form-control col-sm-6" id="employees">
    <option value="0"></option>
    @foreach ($users as $user)
    <option value="{{ $user->id }}">{{ $user->surname . ' ' . $user->name }}</option>
    @endforeach
</select>

And this is the called function (adminArea.blade.php)::这就是所谓的 function (adminArea.blade.php)::

function fillEmployeeData(emp_id) {
    var emp_selected = emp_id.value;
    $.ajax({
        type: "POST",
        url: "{{ route('adminAreaPostEmployee') }}",
        data: 'emp_selected=' + emp_selected,
        success: function (data) {
            var emp_data = JSON.parse(data);
            alert(emp_data);
        }
    });
};

These are my routes (web.php):这些是我的路线(web.php):

Route::get('/adminarea', 'AdminAreaController@index')->name('adminArea');
Route::post('/adminarea/postemployee', 'AdminAreaController@post_employee')->name('adminAreaPostEmployee');

And these are my controller methods (adminAreaController.php):这些是我的 controller 方法(adminAreaController.php):

public function post_employee(Request $request)
{
    $select = $request->get('emp_selected');
    $user = User::where('id', $select);
    echo $user;
}

public function index()
{
    $operations = Operation::all();
    $users = User::all()->sortBy('surname');
    $rooms = Room::all();
    return view('adminArea', compact('users', 'rooms', 'operations'));
}

However, when I change the selected value nothing happens... and if I go to the developer tools I see the following error:但是,当我更改所选值时,什么也没有发生......如果我将 go 发送到开发人员工具,我会看到以下错误:

Failed to load resource: the server responded with a status of 419 (unknown status).加载资源失败:服务器响应状态为 419(未知状态)。 Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException The GET method is not supported for this route. Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException 此路由不支持 GET 方法。 Supported methods: POST.支持的方法:POST。

I don't see any alert.我没有看到任何警报。 Someone can help me?有人可以帮助我吗?

The HTTP status code for the MethodNotAllowedHttpException is 405 MethodNotAllowedHttpException的 HTTP 状态代码为405

See here这里

public function __construct(array $allow, string $message = null, \Throwable $previous = null, ?int $code = 0, array $headers = [])
{
    $headers['Allow'] = strtoupper(implode(', ', $allow));
    parent::__construct(405, $message, $previous, $headers, $code);
}

A TokenMismatchException HTTP status code is 419 A TokenMismatchException HTTP 状态码为419

See here这里

protected function prepareException(Exception $e)
{
    if ($e instanceof ModelNotFoundException) {
        $e = new NotFoundHttpException($e->getMessage(), $e);
    } elseif ($e instanceof AuthorizationException) {
        $e = new AccessDeniedHttpException($e->getMessage(), $e);
    } elseif ($e instanceof TokenMismatchException) {
        // HTTP Status code is send in the header here
        $e = new HttpException(419, $e->getMessage(), $e);
    } elseif ($e instanceof SuspiciousOperationException) {
        $e = new NotFoundHttpException('Bad hostname provided.', $e);
    }
    return $e;
}

So this appears to be a CSRF token issue所以这似乎是一个 CSRF 令牌问题

Make sure that you have a meta tag on the head of your document like this确保您的文档头部有一个元标记,如下所示

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

Also from the JQuery Ajax Documentation也来自JQuery Ajax 文档

I think that the HTTP method should be defined as method parameter not type (though type works ¯\_(ツ)_/¯)我认为 HTTP 方法应该定义为method参数而不是type (尽管type有效¯\_(ツ)_/¯)

// Send a CSRF token header with every Ajax request
$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});
function fillEmployeeData(emp_id) {
    var emp_selected = emp_id.value;
    $.ajax({
        method: "POST",
        url: "{{ route('adminAreaPostEmployee') }}",
        data: 'emp_selected=' + emp_selected,
        success: function (data) {
            var emp_data = JSON.parse(data);
            alert(emp_data);
        }
    });
};

But now you're gonna get an error但是现在你会得到一个错误

Object of class Illuminate\Database\Eloquent\Builder could not be converted to string Object 的 class Illuminate\Database\Eloquent\Builder 无法转换为字符串

Because you're trying to return a query builder instance User::where('id', $select) instead of the user record itself serialized因为您试图返回查询构建器实例User::where('id', $select)而不是用户记录本身序列化

I think you may want to do this我想你可能想这样做

public function post_employee(Request $request)
{
    $select = $request->get('emp_selected');
    return User::find($select);
}

Hope this helps希望这可以帮助

Try to 'method' instead of 'type'.尝试“方法”而不是“类型”。 You should use type if you're using versions of jQuery prior to 1.9.0如果您使用 1.9.0 之前的 jQuery 版本,则应使用 type

function fillEmployeeData(emp_id) {
    var emp_selected = emp_id.value;
    $.ajax({
        method: "POST",
        url: "{{ route('adminAreaPostEmployee') }}",
        data: 'emp_selected=' + emp_selected,
        success: function (data) {
            var emp_data = JSON.parse(data);
            alert(emp_data);
        }
    });
};

this is a CSRF protection of laravel, you can add csrf meta tag in the head这是 laravel 的 CSRF 保护,你可以在头部添加 csrf 元标记

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

and in the top of the script write并在脚本的顶部写

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM