javascript Yii Framework 2.0 检查它是否是来自 AJAX 的 GET 请求
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26335978/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Yii Framework 2.0 check if it is a GET request from AJAX
提问by O Connor
Working with Yii framework 2.0, I have an AJAX GET jQuery script that points to a function in a controller class.
使用 Yii 框架 2.0,我有一个 AJAX GET jQuery 脚本,它指向控制器类中的一个函数。
$.get('localhost/website/index', {param: 'xxxx'}, function(returnedData){
// some code here.....
}, 'json');
In the controller class I have a method as following that handles the AJAX GET request.
在控制器类中,我有一个如下方法来处理 AJAX GET 请求。
public function actionIndex() {
$getParam = $_GET['param'];
// echo $getParam is: 'xxxx'.
// some other code here....
echo json_encode(array());
}
Everything works fine when executing this AJAX GET jQuery script. But if I visit the link localhost/website/indexmanually on the web browser, I get the following error.
执行此 AJAX GET jQuery 脚本时一切正常。但是,如果我在 Web 浏览器上手动访问链接localhost/website/index,则会出现以下错误。
PHP Notice - ErrorException
Undefined index: param
// the code snippet is also being shown.....
I don't want any users to see this error in case they know this link and visit this link by accident or on purpose. If I use
我不希望任何用户看到此错误,以防他们知道此链接并无意或有意访问此链接。如果我使用
if($_GET['param']){...}
I still get the error message on the browser. How can I solve that?
我仍然在浏览器上收到错误消息。我该如何解决?
回答by Adam Fentosi
You can check, that the request is an ajax request with isAjax
:
您可以检查请求是否是一个 ajax 请求isAjax
:
$request = Yii::$app->request;
if ($request->isAjax) {...}
Or you can check that the request is POST or GET
或者您可以检查请求是 POST 还是 GET
if (Yii::$app->request->isPost) {...}
if (Yii::$app->request->isGet) {...}
And always use isset() as well! :)
并且始终使用 isset() !:)
回答by mochalygin
easy way:
简单的方法:
if (isset($_GET['param'])) {
...
}
right way:
正确的方法:
if (isset($_SERVER['HTTP_X_REQUESTED_WITH']
&& strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')
) {
//...
}