gpt4 book ai didi

ajax - 如果浏览操作,则在Grails中重定向用户

转载 作者:行者123 更新时间:2023-12-02 14:38:52 25 4
gpt4 key购买 nike

我有一个用于Ajax的Grails Controller Action ,尽管您仍然可以在浏览器中导航和查看页面。

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功能,是否可以重定向?

最佳答案

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 header 添加到请求中。 Grails将此 isXhr()方法动态添加到HttpServletRequest类。
// test whether the current request is an XHR request
HttpServletRequest.metaClass.isXhr = {->
'XMLHttpRequest' == delegate.getHeader('X-Requested-With')
}

关于ajax - 如果浏览操作,则在Grails中重定向用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1604761/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com