2010-09-05 249 views
0

所以我使用的是form_remote_tag尝试一个ajax表单提交,就像这样: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 action:

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

当我提交表单(通过提交按钮,没有什么奇怪的像jquery submit()e没有ajax请求。 xhr检查返回false。请帮助??

回答

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)。在导轨3中没有form_remote_tag。UJS可以使用with rails 2.3 as well

+0

不应该request.xhr?至少返回true?那个动作就是我用来测试ajax请求是否被发送的东西。 – herpderp 2010-09-05 20:46:52