【问题标题】:How to render the AJAX response in RAILS如何在 RAILS 中呈现 AJAX 响应
【发布时间】:2012-01-10 01:58:48
【问题描述】:

好的,非常简单的问题,我有一个 AJAX 方法,它的作用是在数据库中搜索特定信息并通过查询。我可以在控制台中看到正在进行查询,我什至可以在 Chrome 开发者控制台中看到“发布”,当我点击它时,我可以看到我想要显示的 HTML,但我不知道如何在页面中渲染 ir。

:3000/ 已经有我要显示的 html,但是如何更新呢??

我展示的方式是这样的……

<%if not @itemsok.nil? 
  @itemsok.each do |searches|
%>
<table>
<tr>
  <td style="width:100px;"><%= searches.first_item.description %>  </td>
  <td style="width:150px; font-size:30px;"><%= searches.first_item_grade %>  </td>


  <td style="width:150px;"><%= searches.second_item.description %> </td>
  <td style="width:150px; font-size:30px;"><%= searches.second_item_grade %>  </td>
  <td style="width:150px; font-size:18px;"><a href="<%= contribution_path(searches.id) %>">Show</a>  </td>


</tr>
</table>

@itemsok 是我保存查询项目的变量。

谢谢,我想我在这里遗漏了一些非常愚蠢的东西。 对不起我糟糕的英语。

更新:控制器如下所示:

def index
    size1 = params[:size1]
    number1 = params[:number1]
    number2 = params[:number2]
    quiero = params[:quiero]
    tengo = params[:tengo]

    if (not number1.nil?) and (number1 != "")
      item1 = Item.find(number1)
    elsif not quiero.nil?
      quiero.strip!
      item1 = Item.find(:first, :conditions => ['lower(description) LIKE ?', "%#{quiero.downcase}%"])
    end

    if (not number2.nil?) and (number2 != "")
      item2 = Item.find(number2)
    elsif not tengo.nil?
      tengo.strip!
      item2 = Item.find(:first, :conditions => ['lower(description) LIKE ?', "%#{tengo.downcase}%"])
    end

    if (item1 and item2)

      @itemsok = Contribution.where("first_item_id = ?",item1.id).where("second_item_id = ?",item2.id).where("second_item_grade = ?",size1)


      respond_to do |format|
       format.html
       format.js

      end
    end

【问题讨论】:

  • Ajax 调用所触发的控制器动作是什么样的?我会看看Ruby on Rails tutorial section on Ajax
  • 我将使用控制器操作更新帖子。我已经做了一项研究,问题是我感到困惑,因为在我找到的每个 AJAX 教程中,他们只是做了一个“创建”动作。 :/ 谢谢你的回答。

标签: ruby-on-rails ruby ajax jquery


【解决方案1】:

在您的 respond_to 块中将 format.js 放在 format.html 上方。

确保控制器的视图文件夹中有 index.js.erb。 如果您使用的是 rails 3.1+,则此 index.js.erb(来自操作名称)应该具有如下 jQuery 语句:

$('#DOMelementToPlaceContent').html(<%= escape_javascript(render :partial => "partial/location") %>);

这会将 ID 为 DOMelementToPlaceContent 的 DOM 元素的内容替换为指定部分中的内容。

此外,您应该考虑将搜索逻辑移动到同一控制器中的搜索操作,在这种情况下,您需要控制器的视图文件夹中的 search.js.erb 文件。

【讨论】:

  • 这正是我需要的,我正在使用这个$(document).ready(function(){ $('#formid') .bind("ajax:success", function(evt, xhr, settings){ alert("ok"); $('#foo-list').css('background', 'yellow').html("&lt;%= escape_javascript(render('@itemsok')) %&gt;"); }) });
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-05-19
  • 2014-02-10
  • 2021-04-09
  • 2011-01-28
  • 2018-10-31
  • 1970-01-01
  • 2019-11-02
相关资源
最近更新 更多