假设我有一个标准 Controller 创建操作:
def create
@object = Object.new(object_params)
if @object.save
redirect_to @object, flash: {success: "Created object successfully."}
else
render :new
end
end
现在,如果我将重定向更改为使用涡轮链接:
redirect_to @object, turbolinks: true, flash: {success: "Created object successfully."}
服务器返回一个文本/javascript响应,我的浏览器将其显示为一个白色页面,上面只有这行文本:
Turbolinks.visit('http:/localhost:3000/objects/1');
如何让我的浏览器真正执行该代码而不是将其显示为文本?
另外,如何才能显示刷新成功消息?
最佳答案
这不是对您问题的直接回答。但我建议为此使用不显眼的 JS。您需要首先在表单中添加 remote: true
。
def create
@object = Object.new(object_params)
if @object.save
flash.now.success = 'Created object successfully.'
else
flash.now.alert = @object.errors.full_messages.to_sentence
end
render :js
end
创建一个仅包含以下内容的文件 create.js.erb:
$('#flash').replaceWith("<%= j render partial: 'layouts/flash' %>");
- 这就是 render :js 将被渲染回浏览器的内容,从而执行一个脚本,该脚本将用新的 flash 消息替换您的 flash 容器(#flash 或您使用的任何 id)
- 此外,请确保您有一个包含 Flash HTML 代码的部分 View 文件 app/layouts/_flash.html.erb。
更新:
如果不使用 Unobtrusive JS。您可以像下面这样渲染部分文件:
def create
@object = Object.new(object_params)
if @object.save
flash.now.success = 'Created object successfully.'
else
flash.now.alert = @object.errors.full_messages.to_sentence
end
render partial: 'layouts/flash'
end
然后在 HTML 中嵌入如下内容:
$('#myForm').ajaxForm({
url : '<%= url_for objects_path %>',
type: 'post',
dataType : 'json',
success : function (response) {
$('#flash').replaceWith(response);
}
});
附注您可能还对 Wiselinks 感兴趣它实际上已经做到了这一点(部分 View 加载;您指定要替换的目标容器)。因为目前 turbolinks
尚不支持部分加载,所以它总是加载整个主体。
关于javascript - rails 4 : Turbolinks redirect with flash,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32101360/