我在使用 ajax 请求从 Rails Controller 操作获取响应时遇到了一些奇怪的行为。
$.ajax({
type: 'GET',
url: '/notifications',
success: function(result) {
eval(result);
}
});
def index
respond_to do |format|
format.html { redirect_to root_url, alert: 'Page not accessible' }
format.js
end
end
因此,当使用带有 Rails 的 remote: true
选项的请求时,此 respond_to block 工作正常,但使用 ajax 调用时,它只是将请求重定向到 root_url
。
当指定 json
作为 Ajax 请求的 dataType
时。 so 会很好地返回 JavaScript,但是因为它不是有效的 json
,所以 eval()
不会运行它。
有没有办法从 JavaScript 中启动 Rails 远程请求或指定返回的 JavaScript 可执行的数据类型?
即使在 ajax 调用中指定 dataType: 'text/javascript',
也无济于事。
最佳答案
So this respond_to block works fine when using requests with rails' remote: true option, but with the ajax call it just redirects the request to root_url
因此到达 Controller 的请求格式是HTML
而不是JS
。使用 dataType: 'script'
将请求生成为 JS
并且应该可以解决您的问题。
$.ajax({
type: 'GET',
dataType: 'script',
url: '/notifications'
});
关于javascript - rails : Respond with js to Ajax request,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45658103/