需要将参数传递给ajax文件

时间:2014-06-11 17:56:38

标签: ruby-on-rails ajax

我有一个带有几个按钮的网页,每个按钮通过ajax在页面上加载信息。每个按钮在控制器中调用相同的操作。这个动作叫做'#34; load"然后调用一个ajax文件,该文件依次根据点击的按钮加载页面上的不同信息。

我的html文件中的按钮看起来像这样。

<%= button_to "Load Profile", { :controller => "surveys", :action => "load"} %>
<%= button_to "Load Personality", { :controller => "surveys", :action => "load"} %>
<%= button_to "Load Experience", { :controller => "surveys", :action => "load"} %>

surveys_controller.rb文件中的加载操作类似于

def load
  respond_to do |f|     
    f.js { render 'shared/ajax/info.js.erb' }
  end
end 

info.js.erb文件看起来像这样

$('#email').empty().html("<%= j render(:partial => 'shared/survey/tech/profile') %>")

这在其他地方对我有用,但现在我需要加载的内容不同。我需要&#34; #mail&#34;和#34;共享/调查/技术/简介&#34;作为从加载操作发送的参数。任何人都可以帮助我吗?

2 个答案:

答案 0 :(得分:0)

由于每个按钮都有相同的操作和相同的js.erb文件,因此需要使用按钮发送一些数据才能区分按钮。

为此,您需要按照以下步骤操作:

一个。 为自定义方法创建post请求加载

post  'surveys/load' => "surveys#load"

通过按钮发送一些数据,以区分它们

<%= button_to "Load Profile", { :controller => "surveys", :action => "load", :profile => "yes"} , :method=>:post, :remote => true  %>
# this will make you access params[:profile]

℃。 使用params检查您的加载方法内部点击了哪个按钮:

def load
  @profile = params[:profile]
  #other params to store values of personality and experience
  respond_to do |f|      
    f.js { render 'shared/ajax/info.js.erb' }
  end
end 

d。 在您的info.js.erb文件中,您可以检查哪个变量等于是,然后相应地渲染

<% if @profile == "yes" %>
  #render your partial
<% elsif @personality == "yes" %>
  #render your partial
<% elseif @experience == "yes" %>
  #render your partial
<% end %>

在第二个想法中,我认为如果我们在控制器内部分离出这个逻辑会更好,并且根据params值渲染不同的js文件,如:

def load
  @profile = params[:profile]
  #other params to store values of personality and experience
  if @profile == "yes"
    respond_to do |f|      
      f.js { render 'shared/ajax/profile_info.js.erb' }
    end
  elsif @personality == "yes"
    respond_to do |f|      
      f.js { render 'shared/ajax/personality_info.js.erb' }
    end
  end
end 

答案 1 :(得分:0)

尝试这样的事情,看看它是否适合你;

<%= link_to "Load Profile", { :controller => "surveys", :action => "load"}, remote: true %>
<%= link_to "Load Personality", { :controller => "surveys", :action => "load"}, remote: true %>
<%= link_to "Load Experience", { :controller => "surveys", :action => "load"}, remote: true %>  

respond_to do |form
    format.js { }
end    

然后;

$('#email').empty().html("<%= j render(:partial => 'shared/survey/tech/profile') %>")