Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
329 views
in Technique[技术] by (71.8m points)

php - Laravel - check if Ajax request

I have been trying to find a way to determine Ajax calls in Laravel but I have not found any documentation about it.

I have an index() controller function where I want to handle the response differently based on the nature of the request. Basically this is a resource controller method that is bound to GET request.

public function index()
{
    if(!$this->isLogin())
        return Redirect::to('login');
            
    if(isAjax()) // This is what I am needing.
    {
        return $JSON;
    }

    $data = array(
        'records' => $this->table->fetchAll()
    );

    $this->setLayout(compact('data'));
}

I know the other methods of determining the Ajax request in PHP but I want something specific to Laravel.

Thanks

Updated:

I tried using

if(Request::ajax())
{
    echo 'Ajax';
}

But I am receiving this error:

Non-static method IlluminateHttpRequest::ajax() should not be called statically, assuming $this from incompatible context

The class shows that this is not a static method.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Maybe this helps. You have to refer the @param

         /**       
         * Display a listing of the resource.
         *
         * @param  IlluminateHttpRequest $request
         * @return Response
         */
        public function index(Request $request)
        {
            if($request->ajax()){
                return "AJAX";
            }
            return "HTTP";
        }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...