简体   繁体   English

除非刷新页面,否则Rails ajax的第一个请求不会显示

[英]Rails ajax first request not showing up unless I refresh the page

I have a view that has a form to create a new post using Ajax, and it also renders all the posts and adds the newly added post to them. 我有一个视图,该视图具有使用Ajax创建新帖子的表单,它还呈现所有帖子并将新添加的帖子添加到其中。 The problem is when I post the very first post, the page does not show it unless I refresh, then if I refresh it shows up and when I add more posts Ajax works fine. 问题是,当我发布第一篇文章时,除非刷新,否则页面不会显示它,否则,如果我刷新它就会显示出来,并且当我添加更多文章时,Ajax可以正常工作。

Here is the view index.html.erb : 这是视图index.html.erb

<%= link_to('Logout', destroy_user_session_path, :method => :delete) %>
<%= link_to 'Edit my account', edit_user_registration_path %>
<%= form_tag search_posts_path, method: :get do %>
<%= text_field_tag :search, params[:search] %>
<%= submit_tag "Search", name: nil %>
<% end %>

<b> Study requests </b>

<%= form_for(@post, remote: true) do |f| %>

        <%=f.label :Course_name %>
        <%=f.select :course_name, options_for_select(course_names) %><br/>

        <%=f.label :Course_number %>
        <%=f.select :course_number, options_for_select(course_numbers) %> <br/>

        <%=f.submit %>
<% end %>
<%= render @posts %>

The partial is _post.html.erb : 部分是_post.html.erb

div id="post">
    <%= post.user_name%>
</div>

Controller : 控制器:

def index
        @posts = Post.all.order('id DESC')
        @post = Post.new
    end

    def create
        @post = current_user.posts.build(post_params)

        @post.save
        respond_to do |format|
            format.html { redirect_to @post, notice: "Study request successfully added" }
            format.js {}
            format.json { render json: @post, status: :created, location: @post }
        end
    end

And finally my create.js.erb : 最后是我的create.js.erb

$("<%= escape_javascript(render @post) %>").prependTo("#post");

I got it, I only needed to add a new div around my partial rendering like this : 我知道了,我只需要在局部渲染周围添加一个新的div,就像这样:

<ul id="container">
<%= render @posts %>
</ul>

And change the create.js to append to this div 并更改create.js以追加到此div

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM