Rails AJAX表单保持呈现为HTML

时间:2013-02-03 14:25:39

标签: ruby-on-rails jquery ujs

我正在尝试将一些ajax添加到基本表单中,尽管它仍然呈现为html

OpponentsController处理#create as HTML

我的观点

<%= form_for(@opponent, :remote => true, :url => { :controller => "opponents", :action => "create" }) do |f| %>
  <% if @opponent.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@opponent.errors.count, "error") %> prohibited this opponent from being saved:</h2>

      <ul>
      <% @opponent.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
      </ul>
    </div>
  <% end %>
  <div class="field">
    <%= f.label :name %><br />
    <%= f.text_field :name %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

控制器

# POST /opponents
  # POST /opponents.json
  def create
    @opponent = Opponent.new(params[:opponent])

    respond_to do |format|
      if @opponent.save
        format.html { redirect_to(opponents_url,
                                  :notice => "#{@opponent.name}  was successfully created.") }
        format.js { render }
      else
        format.html { render :action => "new" }
        format.json { render :json => @opponent.errors, :status => :unprocessable_entity }
      end
    end
  end

create.js.erb

alert('Hello Rails');

enter code here

1 个答案:

答案 0 :(得分:1)

AJAX表单要求您加载jquery和jquery_ujs。确保将它们包含在应用程序布局标题中或application.js文件中,如下所示:

# application.js
//= require jquery
//= require jquery_ujs