获取控制器内的环境
我的一个控制器中存在一种情况,只能通过 AJAX 访问,我有以下代码。
if (!$request->isXmlHttpRequest()) {
$response = new Response();
$response->setContent('AJAX requests only!');
return $response;
}
当我测试时,这给我带来了一个问题,因为请求实际上并不是通过 AJAX 发出的。这每次都会破坏我的测试。我应该如何解决这个问题?
我的想法:
- 我尝试设置服务器标头,但完全没有成功。
- 检查我是否在控制器中的测试环境中,如果是则不进行检查。我知道这很脏,但它会起作用。 :-/ 问题是我不知道如何发现我所处的环境。
其他人还有我缺少的任何其他想法或技巧来让上述之一发挥作用吗?
I have a situation in one of my controllers that should only be accessed via AJAX, I have the following code.
if (!$request->isXmlHttpRequest()) {
$response = new Response();
$response->setContent('AJAX requests only!');
return $response;
}
When I am testing this gives me an issue because the request hasn't actually been made via AJAX. This then breaks my tests every time. How should I go about working around this?
My Ideas:
- I have tried to set a server header but have had absolutely no success.
- Check if I am in the test environment in the controller and don't do the check if it is. I know this is dirty, but it would work. :-/ The problem was that I couldn't figure out how to discover what environment I am in.
Anyone else have any other ideas or tips that I am missing to get one of the above to work?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

发布评论
评论(2)
查看 Request
类中的 isXmlHttpRequest
和 ServerBag
类中的 getHeaders
方法的代码,下面的代码应该解决办法:
$client->request(
'GET',
'/path/to/test',
array(),
array(),
array(
'HTTP_X-Requested-With' => 'XMLHttpRequest',
)
);
我没有亲自测试它,但我认为它应该有效。 Request
中的以下代码行用于检查 http 请求是否为 XmlHttpRequest
。
return 'XMLHttpRequest' == $this->headers->get('X-Requested-With');
在代码中,$this->headers
使用以下方法设置:
$this->headers = new HeaderBag($this->server->getHeaders());
getHeaders
方法创建一个标头数组。每个以 HTTP_
开头的服务器变量以及一些特殊的服务器变量(例如 CONTENT_TYPE
)都放入此数组中。
希望这有帮助。
问候,
马特
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
当然,在 Icode4food 的情况下,最好使用 Matt 的解决方案,但这里是如何找到当前环境的:
Of course in Icode4food's case, it's better to use Matt's solution, but here is how to find the current environment: