使用 JavaScript 在 Rails 3 中加载远程表单
我是 Rails 和 javascript 的新手。这可能是一个非常简单的问题,但我仍然无法弄清楚。 目标是,我有一个按钮链接,单击该按钮后应在同一页面上加载地址表单。代码的链接是
<%= link_to "添加地址", new_address_path, {:class => “按钮”},{:远程=>正确}%>
地址文件“addresses/new.html.erb”是:
<div id="newaddr">
<%= render :partial => 'form', :local => @address %>
</div>
表单是“addresses/_form.html.erb”:
<%= form_for(@address, :remote => true) do |f| %>
<%= render 'shared/error_messages', :object => f.object %>
<%= f.text_field :line_1 %>
<%= f.submit %>
<% end %>
javascript 文件“addresses/new.js.erb”:
$('#newaddr').append("<%= escape_javaScript(render 'form', :local => @address) %>");
addresses_controller 文件中的新方法是:
def new
@title = "Add Address"
@address = Address.new
respond_to do |format|
format.js
end
end
但它不起作用。我在这里缺少什么吗?
谢谢!
I am new in rails and javascript. This may be a very simple question but I am still unable to figure it out.
The goal is that, I have a link to button that when clicked should load a address form on the same page. The link to code is
<%= link_to "Add Address", new_address_path, {:class => "button"}, {:remote => true} %>
The address file "addresses/new.html.erb" is:
<div id="newaddr">
<%= render :partial => 'form', :local => @address %>
</div>
The form is "addresses/_form.html.erb":
<%= form_for(@address, :remote => true) do |f| %>
<%= render 'shared/error_messages', :object => f.object %>
<%= f.text_field :line_1 %>
<%= f.submit %>
<% end %>
The javascript file "addresses/new.js.erb":
$('#newaddr').append("<%= escape_javaScript(render 'form', :local => @address) %>");
The new method in addresses_controller file is:
def new
@title = "Add Address"
@address = Address.new
respond_to do |format|
format.js
end
end
But it doesn't work. Is there anything I am missing here?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您收到的错误表明您的链接正在作为普通 HTML 链接执行,而不是 js。你的控制器方法只接受js,所以它返回406,不可接受。
最明显的原因是
rails.js
javascript 未包含在您的application.html.erb
中。通常添加以下行就足够了:或者,如果这不起作用,请明确执行:
希望这会有所帮助。
The error you get indicates that your link is being executed as a normal HTML link, not a js. Your controller method only accepts the js, so it returns the 406, not acceptable.
The most obvious reason for this is that the
rails.js
javascript is not included in yourapplication.html.erb
. Normally adding the following line is sufficient:or, if that does not work, do it explicitly:
Hope this helps.
更改您的 new.js.erb 文件:
Change your new.js.erb file: