Rails form_for :remote=>true 不是调用 js 方法 [英] Rails form_for :remote=>true is not calling js method

查看:35
本文介绍了Rails form_for :remote=>true 不是调用 js 方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道为什么这不起作用,我正在学习 Rails 并且我正在关注一本书,它说这样做:

 <%= form_for([@article,@article.comments.new ], :remote=>true, :html => {:style=>'display: none;' })做 |f|%><div class="field"><%= f.label :name %><%= f.text_field :name %>

<div class="field"><%= f.label :email %><%= f.text_field :email %>

<div class="field"><%= f.label :body %><%= f.text_area :body %>

<%= f.submit %><%结束%>

但是它不起作用,当我在 firebug 中检查请求时,url 没有以 .js 结尾,你知道为什么吗?

解决方案

当你在 firebug 中查看请求时,仅仅因为 url 没有以 .js 结尾,并不意味着它不是从 javascript 调用的.要验证您是否应该检查请求标头以查看 Accept 参数是什么.如果它说应用程序/javascript",那么一切都很好.

其次,开始尝试 :remote => true 时,一个非常常见的问题是所需的 javascript 库未包含在您的代码中.所以我的猜测是您的布局中缺少以下代码:

<%= javascript_include_tag :defaults %><%= csrf_meta_tag %>

如果是这种情况,只需将其包含在布局的 标记中即可.

I have no idea why this is not working, I'm learning rails and I'm following a book it says to do it like this:

    <%= form_for([@article,@article.comments.new ], :remote=>true, :html => {:style=>'display: none;' }) do |f|%>
    <div class="field">
      <%=    f.label :name %>
      <%=    f.text_field :name %>
    </div>
    <div class="field">
      <%=    f.label :email %>
      <%=    f.text_field :email %>
    </div>
    <div class="field">
      <%=    f.label :body %>
      <%=    f.text_area :body %>
    </div>
    <%= f.submit %>
<% end %>

However it does not work, and when I check the request in firebug the url doesnt end in .js, do you have any ideas why?

解决方案

When you check the request made in firebug, just because the url did not end with .js, it does not mean that it was not called from javascript. To verify that you should check the request header to see what the Accept parameter is. If it says "application/javascript" then it's all good.

Secondly, a very common problem when starting to try out the :remote => true is that the required javascript libraries are not included in your code. So my guess is that the following code is missing from your layout:

<%= javascript_include_tag :defaults %>
<%= csrf_meta_tag %>

If that is the case, just include it inside the <head> tag of your layout.

这篇关于Rails form_for :remote=>true 不是调用 js 方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆