javascript - 使用 Ajax 加载 Rails 部分

标签 javascript jquery ruby-on-rails ruby ajax

我已经阅读了大量教程,但似乎无法让它发挥作用。我正在使用acts_as_votable gem,并尝试在有人“喜欢”资源(我的投票模型)时加载“不同”部分。

资源索引:

<div class="votes">
    <% if (current_user.liked? resource) %>
        <!-- Unlike -->
        <%= render(:partial => 'unlike', :locals => {:resource => resource})%>
    <% else %>
        <!-- Like -->
        <%= render(:partial => 'like', :locals => {:resource => resource})%>
    <% end %>
</div>

资源 Controller :

def index
  @resources = Resource.all.order(:cached_votes_up => :desc)
end

def like
  @resource = Resource.find(params[:id])
  @resource.liked_by current_user
  respond_to do |format
    format.html { redirect_to :back }
    format.js { render layout: false }
  end
end

路线

Rails.application.routes.draw do
  resources :resources do 
    member do
      get "like", to: "resources#like"
      get "unlike", to: "resources#unlike"
    end
  end
end

like.js.erb

$('.like_resource').bind('ajax:success', function(){
   $(this).closest('.like_resource').hide();
   $(this).closest('.votes').html('<%= escape_javascript (render partial: 'like', locals: { :resource => resource } ) %>');
});

_like.html.erb

<%= link_to like_resource_path(resource), method: :get, remote: true, class: 'like_resource' do %>
    <button class="ui basic compact icon right floated button vote_count">
        <i class="heart icon" style="color: #F1F1F1"></i> <%= resource.get_likes.size %>
    </button> 
<% end %>

当前功能 - 当我单击“like”按钮时,“like”会被注册,但ajax不会加载部分内容。我需要重新加载页面才能看到更新后的“不同”按钮。

如果我更改 like.js.erb 文件以包含一个简单的链接而不是加载部分内容,则它似乎可以正确加载。

$('.like_resource').bind('ajax:success', function(){
   $(this).closest('.like_resource').hide();
   $(this).closest('.votes').html(' <%= link_to "Unlike", unlike_resource_path(@resource), remote: true, method: :get, class: 'unlike_resource' %>');
});

最佳答案

解决了这个问题!控制台发布了 500 内部错误,但对发生的情况知之甚少。我跳进 log/development.log 并发现了这个错误:

undefined local variable or method `resource'

我在 ajax 部分局部变量调用中缺少一个“@”。将最后一行更改为:

$(this).closest('.votes').html('<%= escape_javascript (render partial: 'like', locals: { :resource => @resource } ) %>');

关于javascript - 使用 Ajax 加载 Rails 部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38298672/

相关文章:

javascript - 相同的选项卡内容显示两次

javascript - event.target/srcElement 在 Chrome 和 Opera 中不能 100% 工作

javascript - Java 连接到网页然后执行 JavaScript

javascript - 您如何将文本样式设置为分数?

jquery - 显示 Ajax 调用进度的最佳方式是什么?

ruby-on-rails - 如何在 Rails 应用程序中为 Heroku 上的生产环境设置邮件程序

javascript - 如何显示和存储按钮值?

javascript - 显示与单击的 id 具有相同类的所有数据

javascript - 用于 SEO 的 URL 重定向(在 Flash 中)?

Java applet 与 Rails 应用程序通信