我一直试图找到一种方法来确定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'));
}
Run Code Online (Sandbox Code Playgroud)
我知道在PHP中确定Ajax请求的其他方法,但我想要一些特定于Laravel的东西.
谢谢
更新:
我试过用
if(Request::ajax())
{
echo 'Ajax';
}
Run Code Online (Sandbox Code Playgroud)
但我收到错误: Non-static method Illuminate\Http\Request::ajax() should not be called statically, assuming $this from incompatible context
该类显示这不是静态方法.
Cra*_*vid 165
也许这有帮助.你必须参考@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";
}
Run Code Online (Sandbox Code Playgroud)
Jna*_*jan 22
要检查ajax请求,您可以使用 if (Request::ajax())
注意:如果您使用laravel 5,则在控制器中更换
use Illuminate\Http\Request;
Run Code Online (Sandbox Code Playgroud)
同
use Request;
Run Code Online (Sandbox Code Playgroud)
我希望它能奏效.
luk*_*ter 19
你使用的是错误的Request课程.如果你想使用Facade:Request::ajax()你必须导入这个类:
use Illuminate\Support\Facades\Request;
Run Code Online (Sandbox Code Playgroud)
并不是 Illumiante\Http\Request
另一种解决方案是注入实际请求类的实例:
public function index(Request $request){
if($request->ajax()){
return "AJAX";
}
Run Code Online (Sandbox Code Playgroud)
(现在你必须导入Illuminate\Http\Request)
Иль*_*ько 13
您可以尝试,$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';
Run Code Online (Sandbox Code Playgroud)
就我而言,我使用了不同的前端代码,并且必须手动放置此标头$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
Run Code Online (Sandbox Code Playgroud)
if(Request::ajax())
Run Code Online (Sandbox Code Playgroud)
看起来是正确的答案. 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
}
Run Code Online (Sandbox Code Playgroud)
小智 5
那些喜欢使用laravel助手的人可以使用laravel helper检查请求是否是ajax request().
if(request()->ajax())
// code
Run Code Online (Sandbox Code Playgroud)