尽管查询字符串参数正确,但Ajax GET请求为空

时间:2019-01-03 22:48:59

标签: php ajax laravel

使用简单的Ajax GET请求检索一些数据,它成功检查了if($request->ajax()) {},但是由于Request $request变量中没有数据,因此验证失败。这仅在生产服务器上发生,在localhost上一切正常。

控制台显示预期的URL https://example.com/employeeInfo?id=1,然后显示错误422(无法处理的实体)。 error: function(jqxhr, status, exception) { alert('Exception:', exception); }的输出给出了空警报消息。

查看

<script>
(function ($) {
$(document).ready(function() {
    $(".team-pic").off("click").on("click", function() {
         $id = $(this).data('id');

         // Get data
         $.ajax({
            type: 'GET',
            url: 'employeeInfo',
            data: {'id':$id},
            success: function(data){
                var obj=$.parseJSON(data);
                // Show output...
            },

             error: function(jqxhr, status, exception) {
                alert('Exception:', exception);
            }
        });

      });
});
}(jQuery));
</script>

路线

Route::get('/employeeInfo', 'EmployeeController@get');

控制器

public function get(Request $request) {

    if($request->ajax()) {

        $this->validate($request, [
            'id' => 'required|integer',
        ]);

        // Id
        $employee = Employee::find(request('id'));

        // Create output
        $data = ...
        echo json_encode($data);

    }
}

1 个答案:

答案 0 :(得分:2)

如果我是你,我将使用带有route model binding的RESTful API,特别是显式绑定。

RouteServiceProvider.php

public function boot() 
{
    parent::boot();
    Route::model('employee', App\Employee::class);
}

路线

Route::get('api/employees/{employee}', 'EmployeeController@get');

控制器

public function get(Employee $employee)
{
    // The id being valid is already done by forcing it to be an Employee
    // It is also an ajax call because it is going to the api route
    // This will json_encode the employee object.
    return $employee;
}