如何判断一个请求是阿贾克斯还是正常的吗? [英] How to determine whether a request is Ajax or Normal?
问题描述
我要以不同方式处理错误的AJAX请求与正常的请求。
I want to handle errors differently for AJAX requests vs normal requests.
我如何确定一个请求是否为AJAX或者不Struts2的行动?
How do I identify whether a request is AJAX or not in Struts2 actions ?
推荐答案
您应该检查是否请求头 X-要求 - 以
是present和等于 XMLHtt prequest
。
You should check if the Request Header X-Requested-With
is present and equals to XMLHttpRequest
.
请注意,并非所有的AJAX请求有这个头,例如 Struts2的道场
请求不发送;如果与 Struts2的-的jQuery
(或任何其他新的AJAX框架),而不是你正在生成AJAX调用,它的存在。
Note that not all the AJAX requests have this header, for example Struts2 Dojo
requests doesn't send it; if you instead are generating AJAX calls with Struts2-jQuery
(or with any other new AJAX framework), it is there.
您可以检查是否是present使用 Firebug的网络模块
...例如,当你投对堆栈溢出;)
You can check if it's present by using Firebug's Net module
... for example, when you vote on Stack Overflow ;)
从内部检查一个 Struts2的行动
,你需要实现 ServletRequestAware
界面,再拿到要求
,并检查特定的头有没有这样的:
To check it from within a Struts2 Action
, you need to implement the ServletRequestAware
interface, then get the Request
and check if that particular header is there like this:
public class MyAction extends ActionSupport implements ServletRequestAware {
private HttpServletRequest request;
public void setRequest(HttpServletRequest request) {
this.request = request;
}
public HttpServletRequest getRequest() {
return this.request;
}
public String execute() throws Exception{
boolean ajax = "XMLHttpRequest".equals(
getRequest().getHeader("X-Requested-With"));
if (ajax)
log.debug("This is an AJAX request");
else
log.debug("This is an ordinary request");
return SUCCESS;
}
}
请注意,您可以通过获得的ActionContext中也要求,没有实现ServletRequestAware接口,但它是不推荐的方式:
Note that you can obtain the request via ActionContext too, without implementing the ServletRequestAware interface, but it is not the recommended way:
HttpServletRequest request = ServletActionContext.getRequest();
这篇关于如何判断一个请求是阿贾克斯还是正常的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!