Rails 3-在弹出窗口中的ajax调用中部分渲染

Ton*_*ony 5 ruby ajax coffeescript ruby-on-rails-3

我有一个带有remote => true的按钮,该按钮以以下方式调用弹出窗口(一个jQuery弹出窗口,不是真正的弹出窗口):

$modal = $('#modal')
$modal_close = $modal.find('.close')
$modal_container = $('#modal-container')
$task_select_div = $('.activity_task_add')

# Handle modal links with the data-remote attribute
$('a[data-remote]').on 'ajax:success',  (xhr, data, status) ->
  $modal
    .html(data)
    .prepend($modal_close)
    .css('top', $(window).scrollTop() + 150)
    .show()

#This is the callback that is not being executed.
$('form[data-remote]').on 'ajax:success',  (xhr, data, status) ->
  alert(data)
  $modal_container.hide()
  $modal.hide()
  $task_select_div.html(data)
Run Code Online (Sandbox Code Playgroud)

在该弹出窗口中,我调用此表单的“提交”按钮中有另一个带有remote_tag的表单,并且在底部具有以下代码的操作:

respond_to do |format|
    if @task.save
       format.html { redirect_to @task, notice: 'Task was successfully created.' }
       format.json { render json: @task, status: :created, location: @task }
       format.js {render :partial => 'tasks', :locals => {:tasks => current_user.department.tasks}}
    else
     format.html { render action: "new" }
     format.json { render json: @task.errors, status: :unprocessable_entity }
    end
end
Run Code Online (Sandbox Code Playgroud)

它执行format.js,并且控制台显示“ Rendered task / _tasks.html.erb(5.8ms)”,但ajax调用的回调不起作用。

$('form[data-remote]').on 'ajax:success',  (xhr, data, status) ->
  alert(data)
Run Code Online (Sandbox Code Playgroud)

我需要接收一个ajax:success事件以隐藏弹出窗口。有什么帮助吗?

Ton*_*ony 1

解决了。

改变了我的response_to do|格式| 为了这:

if request.xhr?
  task_list = render_to_string :partial => 'tasks', :locals => {:tasks => current_user.department.tasks}
  task_list =  task_list.html_safe.gsub(/\n/, '').gsub(/\t/, '').gsub(/\r/, '')
  render :json => {:html => task_list, :error => ''}
else
  respond_to do |format|
    if @task.save
          format.html { redirect_to @task, notice: 'Task was successfully created.' }
          format.json { render json: @task, status: :created, location: @task }  
    else
      format.html { render action: "new" }
      format.json { render json: @task.errors, status: :unprocessable_entity }
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

我的 javascript 是这样的:

$('form[data-remote]').on 'ajax:success',  (xhr, data, status) ->
  $modal_container.hide()
  $modal.hide()
  $task_select_div.html(data.html)
Run Code Online (Sandbox Code Playgroud)

您觉得这个解决方案怎么样?有什么缺点吗?