代码之家  ›  专栏  ›  技术社区  ›  DonX

在Grails控制器中识别Ajax请求或浏览器请求

  •  17
  • DonX  · 技术社区  · 15 年前

    我正在开发一个使用大量Ajax的Grails应用程序。如果请求是Ajax调用,那么它应该给出响应(这部分工作正常),但是如果我在浏览器中键入URL,它应该带我到主页/索引页,而不是请求的页。下面是Ajax调用的GSP代码示例。

    <g:remoteFunction action="list" controller="todo" update="todo-ajax">
    
    <div id ="todo-ajax">
    //ajax call rendered in this area
    </div>
    

    如果我们打字 http://localhost:8080/Dash/todo/list 在浏览器URL栏中,控制器应重定向到 http://localhost:8080/Dash/auth/index

    如何在控制器中验证这一点。

    3 回复  |  直到 15 年前
        1
  •  34
  •   Siegfried Puchbauer    15 年前

    在bootstrap.in it闭包中添加这个动态方法是很常见的做法:

        HttpServletRequest.metaClass.isXhr = {->
             'XMLHttpRequest' == delegate.getHeader('X-Requested-With')
        }
    

    这允许您通过执行以下操作来测试当前请求是否为Ajax调用:

    if(request.xhr) { ... }
    

    最简单的解决方案是在TODO操作中添加如下内容:

    if(!request.xhr) { 
        redirect(controller: 'auth', action: 'index')
        return false
    }
    

    您还可以使用过滤器/拦截器。我已经构建了一个解决方案,在其中我用一个自定义注释注释了所有Ajax操作,然后在一个过滤器中验证了这一点。

    grails app/conf/bootstrap.groovy的完整示例:

    import javax.servlet.http.HttpServletRequest
    
    class BootStrap {
    
         def init = { servletContext ->
    
            HttpServletRequest.metaClass.isXhr = {->
                'XMLHttpRequest' == delegate.getHeader('X-Requested-With')
            }
    
         }
         def destroy = {
         }
    } 
    
        2
  •  4
  •   Dónal    9 年前

    因为颗粒1.1安 xhr 属性已添加到 request 对象,用于检测Ajax请求。其用法示例如下:

    def MyController {
    
      def myAction() {
        if (request.xhr) {
          // send response to AJAX request  
        } else {
          // send response to non-AJAX request
        }
      }
    }
    
        3
  •  3
  •   Topera    13 年前

    通常的方法是让Ajax例程向请求添加一个头部或一个查询字符串,然后检测它。如果您使用的是Ajax库,那么它可能已经提供了这一点。

    看起来您正在使用原型,它添加了 X-Requested-With header set to 'XMLHttpRequest' ;发现这可能是你的最佳选择。