What is the best way, inside a controller, to know if the request is a XMLHTTP one or not (ZF)

試著忘記壹切 提交于 2019-12-11 04:13:37

问题


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
}


来源:https://stackoverflow.com/questions/1322863/what-is-the-best-way-inside-a-controller-to-know-if-the-request-is-a-xmlhttp-o

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!