【问题标题】:Using Ajax to Replace A Page Element Based on an Onclick Event使用 Ajax 替换基于 Onclick 事件的页面元素
【发布时间】:2010-11-30 21:02:18
【问题描述】:

我正在重新提出这个问题,因为我现在对这个问题有了更好的理解。

我有一个包含四个模型的应用程序:用户、产品、品种和季节。

用户
has_many :seasons
has_many :products, :through => :seasons
has_many :varieties, :through => :seasons

产品
has_many :seasons
has_many :users, :through => :seasons
has_many :varieties

百变
belongs_to :product
has_many :seasons
has_many :users, :through => :seasons

季节
belongs_to :product
belongs_to :user
belongs_to :variety

在产品/展示视图中,我列出了可用于特定产品的每个品种,以及携带该特定产品的用户。

当产品/展示页面首次加载时,我会显示所有携带该产品的用户:

<% @product.seasons.each do |c| %>  
  <%= link_to c.user.name, c.user %>  
<% end %>

我还通过这样做列出了产品可用的品种:

<% @product.varieties.each do |c| %>  
  <%= link_to_remote variety.name, :url => variety_path(variety) %>  
<% end %>  

这就是 Ajax 需要发生的地方。当我点击品种名称时,我想用@variety.seasons 替换@product.seasons 循环。我认为这应该只显示具有特定种类的用户。所以看起来像这样:

<% @variety.seasons.each do |c| %>  
  <%= link_to c.user.name, c.user %>  
<% end %>     

我越来越近了,但我无法让它工作。目前,当我点击一个品种时,前端什么也没有发生。在日志中,我得到了这个:

Processing VarietiesController#4 (for ip at 2009-09-24 16:02:29) [POST]
  Parameters: {"authenticity_token"=>"9pDgKrHNbg0aMklsQsGl5BQa34bfr0Ft8Fpbxki3XXw="}
ActionController::UnknownAction (No action responded to 4. Actions: check_vendor_role, index, and show)  

日志引用 #4 并将 4 引用为操作。 4 是我点击的商品的品种 ID。

这是我的设置:

ProductsController#show
@product = Product.find(params[:id])
@varieties = @product.varieties @users = @product.users

产品/展示视图 #列出拥有该产品的用户

<div id="userList">  
  <%= render :partial => "products/users" %>  
</div>  

#Lists the varieties available for this product  

<% @product.varieties.each do |variety| %>  
  <%= link_to_remote variety.name, :url => variety_path(variety) %>  
<% end %>  

VarietiesController#show.

  def show
   @variety = Variety.find(params[:id])
    respond_to do |format|
      format.html
      format.xml  { render :xml => @variety}
      format.js
    end
  end

品种/show.js.rjs
@page.replace_html "userList", :partial => "products/users", :collection => @variety.users

因此,目前,页面正在渲染和显示正确的 html 和数据。但是 onclick 不起作用。当我点击一个品种时,应用程序没有正确处理请求并且用户列表没有改变。

更新

回应 Anatoliy 的评论:

我不确定需要添加什么路线。我尝试添加以下内容,但结果与之前相同:

map.resources :varieties, :member => { :show => :get }

您能否更具体地说明应该调用什么成员路由?

【问题讨论】:

    标签: ruby-on-rails ajax partials page-replacement


    【解决方案1】:

    应该是

    【讨论】:

    • 这是我的问题中的一个错字。我修好了它。还有其他想法吗?
    • 在 config/routes.rb 中应在控制器的 :member 部分声明适当的操作(以避免错误 UnknownAction 没有响应 4 的操作。)
    • 我添加了更新以跟进此问题。我不确定您认为应该添加什么路线。
    • 我想我找到了问题所在。 Ajax 默认使用 POST,但您的路由需要 GET,您应该像这样修复链接: :html => { :method => :get } (我不是 shure 语法,但基本上是想法)
    【解决方案2】:

    如 cmets 所述(应列为答案):

    添加 :method => :get 到您的 link_to_remote 调用以针对该 URL 使用正确的 HTTP 动词“显示”。

    【讨论】:

    • 是的!这就是问题所在。谢谢。
    猜你喜欢
    • 2021-04-06
    • 1970-01-01
    • 2014-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多