gpt4 book ai didi

ruby-on-rails - Rails : rendering the js. erb 模板使用 Controller

转载 作者:行者123 更新时间:2023-12-02 05:31:10 25 4
gpt4 key购买 nike

我有一个 Rails 应用程序试图合并一些 AJAX,单击新建会打开一个模式窗口和一个表单。如果验证错误失败,我希望能够显示验证错误,因此在我的创建操作中,我考虑重新渲染 new.js.erb 文件。这是正确的方法吗?

def create
@place = Place.new(params[:place])
if @place.save
redirect_to places_path, :notice => "Successfully created place"
else
render "new.js.erb"
end
end

我得到的结果是在我的浏览器中转义了 js 文本,例如:
$("#new_grouping").html("<div class=\"modal-header\">\n  <a class=\"close\" data-   dismiss=\"modal\">×<\/a>\n  <h3>Create a new menu section<\/h3>\n<\/div>\n<form accept-charset=\"UTF-8\" action=\"/places/1-mama-s-pizza/groupings\" class=\"simple_form new_grouping\" id=\"new_grouping\" method=\"post\" novalidate=\"novalidate\">

我尝试将各种选项放入渲染 block 但没有运气。有小费吗?

最佳答案

最好的做法是同时支持 AJAX 和非 AJAX 调用,以防用户因任何原因关闭了 javascript。

def create
@place = Place.new(params[:place])

respond_to do |format|
if @place.save
format.html { redirect_to places_path, :notice => "Successfully created place" }
format.js # renders create.js.erb, which could be used to redirect via javascript
else
format.html { render :action => 'new' }
format.js { render :action => 'new' }
end
end
end
render :action => 'new'实际渲染 Controller Action 的模板 new结果为 new.html.erb分别到 new.js.erb取决于它是非 AJAX 还是 AJAX 调用。

new.js.erb去你的 ERB/javascript 代码:
$("#new_grouping").html("<%= escape_javascript(...) %>">

关于ruby-on-rails - Rails : rendering the js. erb 模板使用 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9735866/

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