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?
相关问题
- Views base64 encoded blob in HTML with PHP
- Laravel Option Select - Default Issue
- Carriage Return (ASCII chr 13) is missing from tex
- PHP Recursively File Folder Scan Sorted by Modific
- Can php detect if javascript is on or not?
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.
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.
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.
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.
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: