dongluan6784 2019-01-03 22:48
浏览 121
已采纳

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

Using a simple Ajax GET request to retrieve some data, it successfully checks if($request->ajax()) {} but then fails any validation because there is no data in the Request $request variable. This happens only on the production server, on localhost everything works fine.

The console shows the intended URL https://example.com/employeeInfo?id=1, then error 422 (Unprocessable Entity). Output from error: function(jqxhr, status, exception) { alert('Exception:', exception); } gives an empty alert message.

View

<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

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

Controller

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条回答 默认 最新

  • dongzhi9032 2019-01-03 23:20
    关注

    If I were you, I would use a RESTful API with route model binding, specifically the explicit binding.

    RouteServiceProvider.php

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

    Route

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

    Controller

    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;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置