나는 Laravel에서 ajax 호출을 결정하는 방법을 찾으려고했지만 그것에 관한 문서를 찾지 못했습니다.
나는이 index()
내가 다른 요청의 성격에 따라 핸들 상황에 원하는 기능을. 기본적으로 이것은 GET 요청에 바인딩 된 리소스 컨트롤러 메서드입니다.
public function index()
{
if(!$this->isLogin())
return Redirect::to('login');
if(isAjax()) // This is what i am needing.
{
return $JSON;
}
$data = array();
$data['records'] = $this->table->fetchAll();
$this->setLayout(compact('data'));
}
PHP에서 Ajax 요청을 결정하는 다른 방법을 알고 있지만 Laravel에 특정한 것을 원합니다.
감사
업데이트 :
나는 사용해 보았다
if(Request::ajax())
{
echo 'Ajax';
}
하지만 오류가 발생합니다. Non-static method Illuminate\Http\Request::ajax() should not be called statically, assuming $this from incompatible context
클래스는 이것이 정적 메서드가 아님을 보여줍니다.
답변
아마도 이것이 도움이 될 것입니다. @param을 참조해야합니다.
/**
* Display a listing of the resource.
*
* @param Illuminate\Http\Request $request
* @return Response
*/
public function index(Request $request)
{
if($request->ajax()){
return "AJAX";
}
return "HTTP";
}
답변
ajax 요청을 확인하려면 다음을 사용할 수 있습니다. if (Request::ajax())
참고 : laravel 5를 사용하는 경우 컨트롤러에서
use Illuminate\Http\Request;
와
use Request;
나는 그것이 효과가 있기를 바랍니다.
답변
잘못된 Request
클래스를 사용하고 있습니다. Facade를 다음과 같이 사용하려면 Request::ajax()
이 클래스를 가져와야합니다.
use Illuminate\Support\Facades\Request;
그리고 Illumiante\Http\Request
또 다른 해결책은 실제 요청 클래스의 인스턴스를 주입하는 것입니다.
public function index(Request $request){
if($request->ajax()){
return "AJAX";
}
(이제 여기에서 가져와야합니다 Illuminate\Http\Request
)
답변
$ request-> wantsJson ()
작동하지 않으면 시도 $request->wantsJson()
할 수 있습니다.$request->ajax()
$request->ajax()
JavaScript 라이브러리가 X-Requested-With HTTP 헤더를 설정하면 작동합니다.
기본적으로 Laravel은 js / bootstrap.js에이 헤더를 설정합니다.
window.axios = require('axios');
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
제 경우에는 다른 프런트 엔드 코드를 사용했고이 헤더를 수동으로 넣어야 $request->ajax()
작동했습니다.
그러나 $request->wantsJson()
헤더없이 axios 쿼리를 확인합니다 X-Requested-With
.
// Determine if the current request is asking for JSON. This checks Content-Type equals application/json.
$request->wantsJson()
// or
\Request::wantsJson() // not \Illuminate\Http\Request
답변
if(Request::ajax())
정답 인 것 같습니다.
http://laravel.com/api/5.0/Illuminate/Http/Request.html#method_ajax
답변
AngularJS 프런트 엔드로 작업하는 사람들을 위해 laravel이 기대하는 Ajax 헤더를 사용하지 않습니다. ( 더 읽기 )
AngularJS에 Request :: wantsJson () 사용 :
if(Request::wantsJson()) {
// Client wants JSON returned
}
답변
laravel request()
helper 를 선호하는 사람들은 laravel helper를 사용하여 요청이 ajax인지 확인할 수 있습니다 .
if(request()->ajax())
// code
