如何判断一个请求是Ajax还是Normal?

How to determine whether a request is Ajax or Normal?(如何判断一个请求是Ajax还是Normal?)

本文介绍了如何判断一个请求是Ajax还是Normal?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想对 AJAX 请求和普通请求以不同的方式处理错误.

I want to handle errors differently for AJAX requests vs normal requests.

如何在 Struts2 操作中识别请求是否为 AJAX?

How do I identify whether a request is AJAX or not in Struts2 actions ?

推荐答案

您应该检查请求标头 X-Requested-With 是否存在并且等于 XMLHttpRequest.

You should check if the Request Header X-Requested-With is present and equals to XMLHttpRequest.

请注意,并非所有 AJAX 请求都有此标头,例如 Struts2 Dojo 请求不发送它;如果您使用 Struts2-jQuery(或任何其他新的 AJAX 框架)生成 AJAX 调用,它就在那里.

Note that not all the AJAX requests have this header, for example Struts2 Dojo requests don't send it; if you instead are generating AJAX calls with Struts2-jQuery (or with any other new AJAX framework), it is there.

您可以使用 Firebug 的 Net 模块来检查它是否存在...例如,当您在 Stack Overflow 上投票时;)

You can check if it's present by using Firebug's Net module... for example, when you vote on Stack Overflow ;)

要从 Struts2 Action 中检查它,您需要实现 ServletRequestAware 接口,然后获取 Request 并检查该特定标题是这样的:

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();

这篇关于如何判断一个请求是Ajax还是Normal?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如何判断一个请求是Ajax还是Normal?

基础教程推荐