2009-10-22 39 views
1

雖然您仍然可以導航並在瀏覽器中查看頁面,但我有一個用於Ajax目的的Grails控制器操作。如果瀏覽動作,在Grails中重定向用戶

class QuoteController { 

def quoteService 

/** 
* This page uses the ajaxRandom function defined below to display random quotes. 
*/ 
def random = { 
    def randomQuote = quoteService.getRandomQuote() 
    [quote:randomQuote] 
} 

/** 
* I do not want this to be a valid page, but maintain its use as a simple Ajax method. 
*/ 
def ajaxRandom = { 
    def randomQuote = quoteService.getRandomQuote() 
    response.outputStream << "<q>${randomQuote.content}</q><p>${randomQuote.author}</p>" 
} 
} 

有沒有一種方法,如果有人通過瀏覽器訪問URL,同時在頁面中維護方法的Ajax功能重定向?

回答

2
def ajaxRandom = { 
    if(!request.xhr) { // this calls the dynamic method request.isXhr() 
     redirect action: 'random' 
    } else { 
     def randomQuote = quoteService.getRandomQuote() 
     response.outputStream << "<q>${randomQuote.content}</q><p>${randomQuote.author}</p>" 
    } 
} 

這是可行的,因爲大部分Ajax JS庫都將X-Requested-With標頭添加到請求中。 Grails將此動態方法isXhr()動態添加到HttpServletRequest類。

// test whether the current request is an XHR request 
HttpServletRequest.metaClass.isXhr = {-> 
    'XMLHttpRequest' == delegate.getHeader('X-Requested-With')     
} 
+0

這工作完美!你推薦任何資源來獲得更多的技巧和竅門嗎? – 2009-10-23 11:39:38

0

一個簡單的方法是在通過ajax調用它時向URL追加一個參數, ?ajax = true

然後檢查它並重定向,如果它不存在(例如當用戶使用它的瀏覽器時)。

如果這太容易解決,請檢查請求以查看瀏覽器請求和ajax請求之間的不同之處。

歡呼

0

如果你的AJAX請求總是職位,那麼你可以檢查的方法和假設POST是一個AJAX調用,因爲它是相當困難的,對於普通用戶不小心,在那裏創建一個POST因爲他們總是可以獲得任何URL(如果他們知道的話)

希望這可以幫到你。

相關問題