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 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器