Rails 4 ajax无法使用新数据渲染,呈现空白部分或嵌套

时间:2014-06-20 06:24:44

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

我的观点是渲染,我的js可以工作但是渲染时,js不会在表单提交上呈现新数据

我的js:

 $('#myform').submit(function() {  

    var valuesToSubmit = $(this).serialize();
      $(this).find('textarea').addClass('uneditable-input').attr('disabled', 'disabled');
    $.ajax({
        url: $(this).attr('action'), //sumbits it to the given url of the form
        data: valuesToSubmit,
        type: "POST",
    dataType: "script",
      success: function(res,json){

          alert("done!"); 
        $("#indexstream").html("<%= j render :partial => 'posts', :collection => @posts, :as => :post %>");
        alert("redenred");
        }

    }).complete(function(js){
        //act on result.
      //alert("submitted");


     $("#disabletext").removeClass('uneditable-input').removeAttr('disabled', 'disabled').val('');



      $("#userlink").hide().show("slow").effect('highlight', {color: '#E5F2F7'}, 3000);



    $(function() {
  $("abbr.timeago").timeago();
});




    });


    return false; // prevents normal behaviour

});

});

发布控制器:

def create

    @post = Post.new(post_params) 
    @post.email = current_user.username
    @post.user_id = current_user.id
    @post.firstname = current_user.firstname
    @post.lastname = current_user.lastname
    @post.avatar = current_user.avatar
    @post.school = current_user.school


    respond_to do |format| 
      if @post.save
        format.html { redirect_to posts_path, :notice => '<i class="fa fa-check fa-5x"></i>'.html_safe }
       # format.js   # @current_item = @post 
      format.json { render action: 'index', status: :created, location: @post }

        format.js { render :partial => 'posts', :collection => @posts, :as => :post, :layout => false}

      else

        format.html { render action: 'new' }
       format.json { render json: @post.errors, status: :unprocessable_entity }
      end
    end

  end

发布index.html.erb

<div id="indexstream">

  <%= render :partial => 'posts', :collection => @posts, :as => :post %>
          </div>

_posts.html.erb:

            <div id="streamline"> 

            <div id ="userlink">

              <%= image_tag post.avatar.url(:small), :style => "border-radius: 5px; border: 1px solid #e1e8ed;" %> 
           <%= post.firstname %> <%= " "  %>  <%= post.lastname %><%= " " %>  <%= link_to post.email, user_path(post.user_id), {class: "usernamelink", style: "font-weight: normal;"} %>

  <abbr class="timeago" title="<%= post.created_at.getutc.iso8601 %>" style="float: right; margin-right: 5px; font-size:90%;
                                                                             margin-top: 12px; color: #8899a6; text-decoration: none !important;">
    <%= post.created_at.to_s %>
</abbr>



            <br /><br />
              <% unless post.description == "status" %>
               <div style="background: #EF4836; width: 10px; height: 5px; float: right; margin-top: -58px; text-align: center; border-radius: 10px; color: #fff; padding-top: 2px; padding-bottom: 2px; margin-right: 5px;">
              </div>
            <h1 style="style= z-index: 100000; color: #3399FF "><%= link_to post.title, post_path(post), {class: "usernamelink", style: "color: #3399FF;"} %></h1>


               <% if post.asset1.file? %>
            <%= image_tag post.asset1.url(:small) %><% end %> <% if post.asset2.file? %><%= image_tag post.asset2.url(:small) %><% end %> <% if post.asset3.file? %><%= image_tag post.asset3.url(:small) %><% end %> <% if post.asset4.file? %><%= image_tag post.asset4.url(:small) %>
            <% end %>
              <br /><br />
    <i class="fa fa-map-marker fa-lg" style="margin-right: 5px; margin-left: 5px;"></i>  <%= post.school %>  <div style="float: right; text-align: left; margin-right: 20px;"> <i class="fa fa-usd "></i><%= post.price %></div>

              <% end %>
              <% if post.description == "status" %>
              <div style="background: #2ECC71; width: 10px; height: 5px; float: right; margin-top: -58px; text-align: center; border-radius: 10px; color: #fff; padding-top: 2px; padding-bottom: 2px; margin-right: 5px;">

              </div>
              <h1><%= auto_link( post.title ) %></h1>


                    <% if post.asset1.file? %>
            <%= image_tag post.asset1.url(:small) %><% end %> <% if post.asset2.file? %><%= image_tag post.asset2.url(:small) %><% end %> <% if post.asset3.file? %><%= image_tag post.asset3.url(:small) %><% end %> <% if post.asset4.file? %><%= image_tag post.asset4.url(:small) %>

            <% end %>
             <br /><br />

              <% end %>






           </div>
         </div>  

jquery高亮效果有效,但它突出显示提交前的最后一个帖子,它隐藏和取消隐藏它。提交表单后新数据在哪里?

由于

更新

帖子索引方法:

 before_action :authenticate_user!
  before_action :set_post, only: [:show, :edit, :update, :destroy]
  respond_to :js, :json, :html


    def index
    @search = Post.search do #Post.search do
      fulltext params[:search]
      with(:school, current_user.school)
      paginate :page => params[:page], :per_page => 20 
      order_by(:updated_at, :desc)  
       end
    @posts = @search.results
  end

**更新2 **

Imgur

控制器:

  before_action :authenticate_user!
  before_action :set_post, only: [ :show, :edit, :update, :destroy]
  respond_to :js, :json, :html

def create

    @post = Post.new(post_params) 
    @post.email = current_user.username
    @post.user_id = current_user.id
    @post.firstname = current_user.firstname
    @post.lastname = current_user.lastname
    @post.avatar = current_user.avatar
    @post.school = current_user.school


    respond_to do |format| 
      if @post.save

       puts "----------#{@posts.inspect}-------------"
       format.html { redirect_to posts_path, :notice => '<i class="fa fa-check fa-5x"></i>'.html_safe }

       format.json {render json: @post, status: :created, location: @post }
      #format.json { render action: 'index', status: :created, location: @post }
        @posts = Post.all
        puts "----------#{@posts.count}-------------"
         format.js { render :partial => 'post', :collection => @posts, :as => :post, :layout => false }
        puts "-------------#{request.format}----------------"
      else
        format.html { render action: 'new' }
       format.json { render json: @post.errors, status: :unprocessable_entity }
        #format.js {alert("couldn't create post")}

      end
    end

  end



def set_post
      @post = Post.find(params[:id])
    end

1 个答案:

答案 0 :(得分:1)

您正在为远程请求的集合呈现部分帖子。但是在你的ajax调用的成功函数中有一行:

$("#indexstream").html("<%= j render :partial => 'posts', :collection => @posts, :as => :post %>");

如果您将上面的代码放在没有.js扩展名的.erb文件中,您将无法在js中使用rails helper methods render和@posts。

如果您正在获得正确的html响应控制器。在ajax成功回调中你只需要做:

$("#indexstream").html(res);

<强>更新

此外,为了在成功创建提交的帖子后获取@posts实例中的所有帖子,您可以修改创建操作,如下所示。

def create

    #
    #
    #


    respond_to do |format| 
      if @post.save
        @posts = Post.all # This will include the @post that is saved right now.
        format.html { redirect_to posts_path, :notice => '<i class="fa fa-check fa-5x"></i>'.html_safe }
       # format.js   # @current_item = @post 
      format.json { render action: 'index', status: :created, location: @post }

        format.js { render :partial => 'posts', :collection => @posts, :as => :post, :layout => false} # This block will render partial posts for collection @posts which is set above.

      else

        format.html { render action: 'new' }
       format.json { render json: @post.errors, status: :unprocessable_entity }
      end
    end

  end

注意:如果使用上述代码,请不要在任何前置过滤器中设置@posts。

更新2

您没有在创建操作中的任何位置设置@posts,请设置为:

...
def create

    @post = Post.new(post_params) 
    @post.email = current_user.username
    @post.user_id = current_user.id
    @post.firstname = current_user.firstname
    @post.lastname = current_user.lastname
    @post.avatar = current_user.avatar
    @post.school = current_user.school


    respond_to do |format| 


      @posts = Post.all # this will set the @posts and you will get the partial render working.



      if @post.save

       puts "----------#{@posts.inspect}-------------"
       format.html { redirect_to posts_path, :notice => '<i class="fa fa-check fa-5x"></i>'.html_safe }

       format.json {render json: @post, status: :created, location: @post }
      #format.json { render action: 'index', status: :created, location: @post }

        puts "----------#{@posts.count}-------------"
         format.js { render :partial => 'post', :collection => @posts, :as => :post, :layout => false }
        puts "-------------#{request.format}----------------"
      else
        format.html { render action: 'new' }
       format.json { render json: @post.errors, status: :unprocessable_entity }
        #format.js {alert("couldn't create post")}

      end
    end

  end
...

同样在js代码中:

 $('#myform').submit(function() {  

    var valuesToSubmit = $(this).serialize();
      $(this).find('textarea').addClass('uneditable-input').attr('disabled', 'disabled');
    $.ajax({
        url: $(this).attr('action'), //sumbits it to the given url of the form
        data: valuesToSubmit,
        type: "POST",
    dataType: "script",
      success: function(response){
        $("#indexstream").html(response); // you might want to console the response here.
      }

    }).complete(function(js){

       //...
       //...
相关问题