【问题标题】:Simple link_to_remote function - can't get it to work简单的 link_to_remote 功能 - 无法让它工作
【发布时间】:2026-01-08 22:05:02
【问题描述】:

在经历了一个多小时的反复试验以及数十篇教程和博客发布示例之后,我仍然无法让简单的 ajax 功能正常工作。这是我的部分内容:

<span id="friend">
  <%= link_to_remote image_submit_tag("/images/add_as_friend.gif"), :url => {:controller => 'friends', :action => 'add', :id => id} %>
</span>

这是我的控制器中的内容:

class FriendsController < ApplicationController
  def add
    unless params[:id].nil?
      Friend.create(:user_id => @current_user.id, :friend_id => params[:id], :friend_type => 2)
    end
  end
end

这是我的 add.rjs 文件中的内容:

page.replace_html 'friend', "A request to be friends with this player has been sent."

链接的图像很好。但是,当我单击它时,什么也没有发生。我检查了数据库,没有任何反应。我一定是错过了什么,有什么想法吗?

【问题讨论】:

    标签: ruby-on-rails ajax


    【解决方案1】:

    这可能是因为您的链接内容使用的是image_submit_tag 而不是image_tagimage_submit_tag 用于提交表单,因此会有自己的点击行为,这可能会覆盖将作为link_to_remote 功能的一部分添加的点击行为。

    我会尝试:

    <%= link_to_remote image_tag("/images/add_as_friend.gif"), 
        :url => {:controller => 'friends', :action => 'add', :id => id} %>
    

    【讨论】:

    • 除此之外,我没有从动作中渲染任何东西。我添加了 line-render :partial => 'friend' 现在它工作顺利。谢谢!