【问题标题】:ajax request with form_remote_tag doesn't work带有 form_remote_tag 的 ajax 请求不起作用
【发布时间】:2010-09-05 07:42:24
【问题描述】:

所以我使用 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。请帮忙??

【问题讨论】:

    标签: ruby-on-rails ajax


    【解决方案1】:

    在控制器中,您应该响应指定的格式,在您的情况下为 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

    【讨论】:

    • 不应该 request.xhr 吗?至少返回 true 吗?该操作只是我用来测试是否正在发送 ajax 请求的操作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-21
    • 2012-11-28
    • 2014-12-28
    • 2017-02-11
    • 2016-05-08
    相关资源
    最近更新 更多