从数据库中检索数据并将其发送到laravel中的ajax

时间:2018-05-30 12:49:28

标签: mysql json ajax laravel laravel-query-builder

我有laravel项目,我想从数据库中检索数据并将其发送到ajax函数 这是show($ ip)函数的代码

  public function show($id)
  {


 $result = DB::table('radcheck')get();
  return ( $result);
  //
   }

这是ajax的代码,它试图从该函数中检索数据,但它不能

     $('.edit-user').on('click', function() {
       var id=$(this).data('id');
        $.ajax({
            type: 'GET',
            url: '/users/' + id,
            data: {
                '_token': $('input[name=_token]').val(),
            },
            success: function(hr_request) {


                alert(hr_request['username']);


            },
              error: function(hr_request) {

                  alert(hr_request['username']);




            }

        });
    });

没有数据可以检索,我想我必须使用json数据从控制器向ajax发送数据,但是如何将其作为json数据发送,如何将此json数据处理为ajax函数

1 个答案:

答案 0 :(得分:1)

很简单..你可以这样做:

public function show($id)
{
  $result = DB::table('radcheck')->get();
  return response()->json(['data' => $result]); // here 'data' is key to access $result in ajax response , it is optional.

}

在ajax响应中,您可以使用console.log(hr_request.data)来控制它,并检查您的数据结果。此外,要访问属性,您需要执行 hr_request.data.property

希望它有所帮助,谢谢。

相关问题