What is the best way, inside a controller, to know

2019-08-04 07:02发布

I have different logic in an action depends if the request is an AJAX one or not.
(For AJAX logins, I do not need to redirect after successful login, which is not the case in normal login, for example).
What is the best way, beside checking the headers for X-Requested-With: XMLHttpRequest
Is there a flag or something?

4条回答
不美不萌又怎样
2楼-- · 2019-08-04 07:29

This method works by checking for a header which is set by almost (if not) all of the major JS libraries, including jQuery and YUI.

$this->getRequest()->isXmlHttpRequest() //returns true if is XHR

The method detailed by smack0007 is guaranteed to be accurate, but the method above is fine if the connection is always made by a library which sets the header. It is probably not suitable for a public API.

查看更多
劳资没心,怎么记你
3楼-- · 2019-08-04 07:29

Usually I create a two entry points for my app: /index.php and /ajax/index.php. They both share a common bootstrapper but in the ajax.php I set a FrontController param to say that this request is an ajax request.

I can then just check in with the Request object.

if($this->getRequest()->getParam('ajax')) {
    // Ajax request
} else {
    // Normal request
}
查看更多
放我归山
4楼-- · 2019-08-04 07:38

There isn't a reliable method to tell them apart; browsers use pretty much the same HTTP code for both XMLHttpRequest and normal access.

With the different browser handling of custom headers, and potential proxy interference, I would not trust the X-Requested-With header to get through in all cases. (And that's all isXmlHttpRequest actually looking for.)

Instead, I'd use a parameter (?ajax=1) or other method that generates a unique URL such as smack's suggestion.

查看更多
时光不老,我们不散
5楼-- · 2019-08-04 07:43

The Zend_Controller_Request_Http class has a method called isXmlHttpRequest() that should tell you whether or not the request is from Javascript (ajax).

(Out of practice coding but) Probably would be something like this in your action:

if($this->getRequest()->isXmlHttpRequest()){
    //is ajax
}
else{
    //regular request
}
查看更多
登录 后发表回答