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

2019-08-04 07:13发布

问题:

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?

回答1:

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.



回答2:

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.



回答3:

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:

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
}