【问题标题】:rails render partial after ajax get request在ajax获取请求后rails呈现部分
【发布时间】:2013-06-02 16:10:17
【问题描述】:

我在我的 Rails 3 应用程序中使用了 Jvectormap。 当我点击它时,我想隐藏地图并可视化包含所选国家信息的部分。

我处理地图点击并向服务器发送 GET 请求。

users.js.coffee.erb

$ ->
  $("#world-map").vectorMap
    onRegionClick: (event, code) ->
      $('#world-map').hide(1000)
      $.get('/users/statistics', {code: code});
      $('#statistics').show(1000)

users_controller.rb

def statistics
 @country = Country.find_by_two_letter_code((params[:code]).downcase)  
 render :nothing => true

结束

这是回复

在 2013-06-02 17:54:49 +0200 开始 GET "/users/statistics?code=ET" for 127.0.0.1

由 UsersController#statistics 处理为 /

参数:{"code"=>"ET"}

Country Load (0.2ms) SELECT "countries".* FROM "countries" WHERE

"countries"."two_letter_code" = 'et' LIMIT 1

渲染文本模板(0.0ms)

在 2 毫秒内完成 200 次 OK(查看次数:0.6 毫秒 | ActiveRecord:0.2 毫秒)

还有风景

show.html.erb

 <p> <div id="world-map" style="width: 620px; height: 300px"></div>
      <div id="statistics" style="width: 620px; height: 300px; display:none;">
       <section>
        <%= render partial:'statistics', :locals => {:country => @country}  %>
      </section>
      </div>
    </p>

_statistics.html.erb

<%= link_to '<i class="icon-remove"></i>'.html_safe%>
<%=country%>
<%=@country%>

现在,一切正常,但部分无法显示国家/地区价值。 我不明白是否必须在 ajax 获取请求后重新渲染部分,以及如何。

我尝试用另一种方式更改控制器,但行为相同。

def statistics
 @country = Country.find_by_two_letter_code((params[:code]).downcase)  
 render 'users/_statistics'
end

【问题讨论】:

  • 尝试使用 respond_whit @country 代替渲染 xxxx ?

标签: ruby-on-rails ajax render partial


【解决方案1】:

我认为既然你不需要刷新页面,只需要显示国家的详细信息,你可以使用ajax。

show.html

<p> <div id="world-map" style="width: 620px; height: 300px"></div>
  <div id="statistics" style="width: 620px; height: 300px; display:none;">
   <section>
    <div id="place_partial_here"></div>
  </section>
  </div>
</p>

在控制器中

def statistics
  @country = Country.find_by_two_letter_code((params[:code]).downcase)  
  respond_to do |format|
    format.js
  end
end

在 statistics.js.haml #我对 haml 很满意。

$('#place_partial_here').replaceWith("#{escape_javascript(render partial: 'country_data', locals: {country: @country})}");

在 _country.html.haml

#place_partial_here #id is denoted in haml using hash
  = country.name #display country name
  = country.code #display code

partial 必须在 id 'place_partial_here' '内部'有视图代码,以便在进一步的 ajax 调用中使用它

【讨论】:

  • 你能写出正确的英文吗(没有你,你之类的)?
【解决方案2】:

你试过了吗

渲染 :partial => "统计", :collection => @country

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-19
    • 1970-01-01
    • 2016-09-12
    相关资源
    最近更新 更多