我正在尝试将 jQuery 与 Rails 和 AJAX 结合使用来接受用户的帖子,并更新页面上的相关元素以显示新帖子。
我已经在我的应用程序中成功设置了一个帖子模型和 Controller ,并对其进行了调整以接受使用 AJAX 的表单提交。我知道 AJAX 表单提交正在工作,但我无法重新加载页面上的任何元素。我有一个 Post 模型、Posts Controller 、一个 _post_form.html.erb 部分,其中有一个用于发布的 html 表单,以及相关的 create.js.erb 文件。
create.js.erb 文件当前包含(不包含“what_to_put_here”):
alert('ajax works!');
$('#user_info').what_to_put_here?
当它只包含警报时,文件将起作用并出现一个显示消息的对话框。所以,我确信一切正常。但是,我只是不知道用户需要什么代码来更新 user_info 元素和 posts 表。我在 javascript 中使用 jQuery 和 jQuery UI。
那么,如何在 create.js.erb 文件中编写更新 posts 表和 user_info current_user.posts.count 的方法?
以下是show.html.erb文件:
<section>
<%= render 'shared/discussion_overview' %>
<% unless @posts.nil? %>
<h3> Thoughts and Opinions </h3>
<table class= "posts">
<%= render @posts %>
</table>
<%= will_paginate(@posts) %>
<% end %>
<%= render 'posts/post_form' %>
</section>
帖子部分_post.html.erb:
<tr>
<td >
<span class="post_header"><h4><%= link_to "#{post.user.first_name} #{post.user.last_name}", post.user %></h4></span>
<p> <%= post.content %> </p>
</td>
</tr>
以及 _user_info.html.erb 部分(从 application.html.erb 引用):
<div id="user_info">
<h1><a href = "<%= user_path(current_user) %>" >
<%= "#{current_user.first_name} #{current_user.last_name}" %>
</a></h1>
<%= pluralize(current_user.posts.count, "post") %> <br>
<%= pluralize(current_user.discussions.count, "discussion")%> <br>
Joined <%= time_ago_in_words(current_user.created_at)%> ago.
</div>
最佳答案
$('#user_info').html("<%= escape_javascript(render :partial => 'user_info')%>");
关于jquery - 在 ruby-on-rails 应用程序上使用 AJAX 提交表单后,如何让 jQuery 更新页面上的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6600620/