使用form_remote_tag的ajax请求不起作用

时间:2010-09-05 07:42:25

标签: ruby-on-rails ajax

所以我使用form_remote_tag尝试提交ajax表单,如下所示:

<% form_remote_tag :update=> 'test', :url=> {:action=>'test_action'} do -%>

它呈现没有明显问题:

<form action="/pages/test_action" method="post" onsubmit="new Ajax.Updater('test', '/pages/test_action', {asynchronous:true, evalScripts:true, parameters:Form.serialize(this)}); return false;">

test_action操作:

def test_action
  if request.xhr?
    render :text => 'some text'
  else
    puts 'nope'
  end
end

当我提交表单时(通过提交按钮,没有像jquery submit()事件那样奇怪),没有提出ajax请求。 xhr检查返回false。请帮忙??

1 个答案:

答案 0 :(得分:0)

在控制器中,您应该响应指定的格式,在您的情况下为js。例如:

def create
  @item = Item.new(params[:item])

  respond_to do |format|
    if @item.save
      flash[:notice] = 'Item was successfully created.'
      format.js
      format.html { redirect_to(@item) }
      format.xml  { render :xml => @item, :status => :created, :location => @item }
    else
      format.html { render :action => "new" }
      format.xml  { render :xml => @item.errors, :status => :unprocessable_entity }
    end
  end
end

目前最好的做法是使用unobtrusive javascript(UJS)。 rails 3中没有form_remote_tag。可以使用UJS with rails 2.3 as well

相关问题