在Rails 5中使用respond_with时的空体

时间:2017-10-31 18:33:28

标签: javascript ruby-on-rails ajax ruby-on-rails-5.1 responders

我正在尝试使用ajax(在成功时)从rails 5中的控制器渲染部分,但是在操作呈现部分后,空白数据将传递给ajax。

相同的代码正在使用rails4。我也为rails5更新了响应者gem。

控制器:

 respond_with do |format|
    format.html do
      if request.xhr?
        @images = get_images
        session[:prev_images] = submitted_ids
        session[:prev_winner] = winner_id
        @prev_images = Lentil::Image.find(submitted_ids).sort_by{ |i| i.id }
        @prev_winner = session[:prev_winner]

        render :partial => "/lentil/thisorthat/battle_form", :locals => { :images => @images, :prev_images => @prev_images, :prev_winner => @prev_winner }, :layout => false, :status => :created
      end
  end

的Ajax:

 $(document).on('ajax:success', function (evt, data, status, xhr) {
    // Insert new images into hidden div
    $('.battle-inner:eq(1)').replaceWith(data);

    $('.battle-inner:eq(1)').imagesLoaded()
        .done(function () {
             // Remove old images
            $('.battle-wrapper:eq(0)').remove();

            // Div with new images moves up in DOM, display
            $('.battle-wrapper:eq(0)').show();

            // Hide Spinner
            $('#spinner-overlay').hide();
    });

_battle_form:

<div class="grid battle-inner">
  <%= semantic_form_for :battle, :remote => true, :url => thisorthat_result_path do |form| %>
      <% @images.each do |image| %>
      <div class="battle-image-wrap grid__cell">
      </div>
      <% end %>
 <% end %>
</div>

2 个答案:

答案 0 :(得分:0)

您的请求是否以JS格式处理?

尝试将format.html替换为format.js

答案 1 :(得分:0)

这是jquery-ujs的问题,它不再是rails&gt; 5.1的依赖项。需要使用rails-ujs依赖。

https://blog.bigbinary.com/2017/06/20/rails-5-1-has-dropped-dependency-on-jquery-from-the-default-stack.html

//从响应中读取数据

.on('ajax:error', function(event) {
    var detail = event.detail;
    var data = detail[0], status = detail[1],  xhr = detail[2];
    // ...
});
相关问题