Ajax(Asynchronous JavaScript and XML)允许网页在不刷新整个页面的情况下与服务器交换数据并更新部分内容。在 Rails 中,通过 remote: true
属性和 UJS(Unobtrusive JavaScript)驱动实现 Ajax 交互。
弹出消息通常通过以下方式实现:
alert()
或自定义模态框(如 Bootstrap Modal)flash
消息通过 Ajax 响应返回步骤 1:添加 remote: true
到表单
<%= form_with(model: @post, remote: true) do |form| %>
<%= form.text_field :title %>
<%= form.submit %>
<% end %>
步骤 2:控制器响应 Ajax 请求
# app/controllers/posts_controller.rb
def create
@post = Post.new(post_params)
respond_to do |format|
if @post.save
format.html { redirect_to @post, notice: 'Post created!' }
format.js # 对应 create.js.erb
else
format.html { render :new }
format.js { render :create_error }
end
end
end
步骤 3:创建 JavaScript 视图模板
# app/views/posts/create.js.erb
<% if flash[:notice].present? %>
alert('<%= j flash[:notice] %>');
// 或使用 Toastr(需提前引入库)
// toastr.success('<%= j flash[:notice] %>');
<% end %>
# create.js.erb
Swal.fire({
icon: 'success',
title: 'Success!',
text: '<%= j @post.title %> was created.',
confirmButtonText: 'OK'
}).then((result) => {
if (result.isConfirmed) {
window.location = '<%= posts_path %>';
}
});
问题 1:弹出消息不显示
format.js
或缺少视图文件。respond_to :js
.js.erb
文件问题 2:消息内容未转义导致 XSS 风险
j
或 escape_javascript
转义:j
或 escape_javascript
转义:问题 3:多次重复弹出
toastr
或原生 alert
SweetAlert2
支持自定义按钮和回调完整示例项目结构:
app/
views/
posts/
create.js.erb
create_error.js.erb
layouts/
application.html.erb # 包含 JS 库
通过以上方案,可实现灵活可靠的 Ajax 消息交互,满足不同场景需求。
没有搜到相关的文章