ajax成功后渲染部分

时间:2015-04-11 10:16:19

标签: jquery ruby-on-rails ajax ruby-on-rails-4 haml

我有以下代码来执行ajax调用并呈现部分:

$("#save-category").click(function(){
    var category_id = $('#categorization_category_id').val();
    var category_name = $('#categorization_category_id  option:selected').text();
    var user_id = "#{current_user.id}";
    $.ajax({
      url: "#{dashboard_categorizations_path}",
      type: 'POST',
      dataType : 'json',
      data: {'user_id': user_id, 'category_id': category_id},
      success: function(data) {
        $("#categoriamensaje").show();
        $('.categories').html("#{escape_javascript(render('tutor_categories'))}");
        var leadMessage = setInterval(function(){
              $("#categoriamensaje").hide();
            }, 3000);
      },
      error: function(xhr, desc, err) {
        console.log(xhr);
        console.log("Details: " + desc + "\nError:" + err);
      }
    }); // end ajax call
  });

除渲染部分外,一切正常。

这是haml代码:

.row
  .col-md-2
  .col-md-5
    %h3
      = _("Tus Categorias")
    .categories
      = render partial: 'tutor_categories'
  .col-md-4

我的控制器代码:

def create
    @categorization = Categorization.new(categorization_params)
    @categorization.save
    respond_to do |format|
      format.json {  render json: {id: @categorization.id.to_json},  success: 200  }
    end
  end

由于

1 个答案:

答案 0 :(得分:0)

根据我们在聊天中的讨论,您需要添加新的categorization条记录,而不是替换整个列表。

您的HAML将成为:

.row
  .col-md-2
  .col-md-5
    %h3
      = _("Tus Categorias")
    .categories
      = render partial: 'tutor_categories', collection: @user_categories, as: :category 
  .col-md-4

您的部分内容将如下:

.badge-tutor{style:"margin: 2px;"} 
  = link_to "<i class='fa fa-tag'></i> #{category.name} <i class='fa fa-times-circle fa-1x' style='color:#A21F1F;'></i>".html_safe, dashboard_categorization_path(category.id), method: :delete, data: { confirm: 'Eliminar esta categoria?' }, style: "color:#fff;text-decoration: none;font-size: 15px;"

控制器:

def create
  @categorization = Categorization.new(categorization_params)
  @categorization.save

  respond_to do |format|
    format.json {render json: {category: @categorization},  success: 200}
  end
end

在您的AJAX调用中,您需要将部分渲染代码更新为:

$('.categories').html("#{escape_javascript(render(:partial => 'tutor_categories', :locals => {:category => data.category}))}");