![](/img/trans.png)
[英]Jquery.ajax request to update a page with a partial template in ruby-on-rails
[英]How can i get jQuery to update an element on a page after submitting a form with AJAX on a ruby-on-rails app?
我正在尝试将 jQuery 与 Rails 和 AJAX 一起使用来接受用户的帖子,并更新页面上的相关元素以显示新帖子。
我已经在我的应用程序中成功设置了 model 和 controller 帖子,并对其进行了调整以接受带有 AJAX 的表单提交。 我知道 AJAX 表单提交工作正常,但我无法让页面上的任何元素重新加载。 I have a Post model, Posts controller, a _post_form.html.erb partial that has a html form for posting, and the relevant create.js.erb file.
create.js.erb 文件当前包含(没有 what_to_put_here):
alert('ajax works!');
$('#user_info').what_to_put_here?
当它只包含警报时,文件可以工作,并出现一个显示消息的对话框。 所以,我确信一切正常。 但是,我只是无法弄清楚用户使用什么代码来更新 user_info 元素和帖子表。 我正在为我的 JavaScript 使用 jQuery 和 jQuery UI。
那么,如何在 create.js.erb 文件中写入更新帖子表和 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')%>");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.