Yii Framework 2.0检查它是否是来自AJAX的GET请求

O C*_*nor 3 javascript php ajax jquery yii2

使用Yii framework 2.0,我有一个AJAX GET jQuery脚本,它指向控制器类中的一个函数.

$.get('localhost/website/index', {param: 'xxxx'}, function(returnedData){
    // some code here.....
}, 'json');
Run Code Online (Sandbox Code Playgroud)

在控制器类中,我有一个处理AJAX GET请求的方法.

public function actionIndex() {
     $getParam = $_GET['param'];
     // echo $getParam is: 'xxxx'.

     // some other code here....

     echo json_encode(array());
}
Run Code Online (Sandbox Code Playgroud)

执行这个AJAX GET jQuery脚本时一切正常.但是,如果我在Web浏览器上手动访问链接localhost/website/index,我会收到以下错误.

PHP Notice - ErrorException
Undefined index: param

// the code snippet is also being shown.....
Run Code Online (Sandbox Code Playgroud)

我不希望任何用户看到此错误,以防他们知道此链接并偶然或故意访问此链接.如果我使用

if($_GET['param']){...}
Run Code Online (Sandbox Code Playgroud)

我仍然在浏览器上收到错误消息.我怎么解决这个问题?

Ada*_*osi 14

您可以检查请求是否为ajax请求:

$request = Yii::$app->request;
if ($request->isAjax) {...}
Run Code Online (Sandbox Code Playgroud)

或者您可以检查请求是POST还是GET

if (Yii::$app->request->isPost) {...}
if (Yii::$app->request->isGet) {...}
Run Code Online (Sandbox Code Playgroud)

并始终使用isset()!:)