Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/362.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Rails 4 JavaScript/JQuery仅对单行view.html.erb文件进行部分更新_Jquery_Ruby On Rails 4 - Fatal编程技术网

Rails 4 JavaScript/JQuery仅对单行view.html.erb文件进行部分更新

Rails 4 JavaScript/JQuery仅对单行view.html.erb文件进行部分更新,jquery,ruby-on-rails-4,Jquery,Ruby On Rails 4,我有一个控制器: class RuleSearchController < ApplicationController def index end def results # Rule is a simple AR class with just a name column @rules = Rule.all end end 然后我有一个results.js.erb,根据添加了本地人来传递我的搜索结果 $('#search_results').html

我有一个控制器:

class RuleSearchController < ApplicationController
  def index

  end

  def results
    # Rule is a simple AR class with just a name column
    @rules = Rule.all
  end
end
然后我有一个results.js.erb,根据添加了本地人来传递我的搜索结果

$('#search_results').html('<%= render partial: "results", locals: {rules: @rules} %>');
$('#搜索结果').html('');
问题在于,虽然以下内容适用于_results.html.erb文件:

<ul><% for rule in rules do %><li><%= rule.name %></li><% end %></ul>
以下代码相同但超过几行,但不适用:

<ul>
<% for rule in rules do %>
  <li><%= rule.name %></li>
<% end %>
</ul>
事实上,除了在_results.html.erb文件中使用一行之外,执行任何操作都不会导致任何事情发生。Chrome上的JS控制台中没有错误,rails服务器运行的终端窗口中没有错误,日志中没有错误,只是安静地不工作

这个问题甚至在基本HTML上也会出现,如果我把本地人带出去也没有帮助

解决方案/解决方法是:

$('#search_results').html('<%= (render partial: "results", locals: {rules: @rules}).gsub("\n","").html_safe %>');
$('#搜索结果').html('');

虽然neuronaut对我最初问题的回答是正确的,但这是因为javascript不允许字符串跨多行拆分。例如,以下是有效的javascript:

$('#search_results').html('<div>foo</div>');
$('search#u results').html('foo');
但以下内容无效:

$('#search_results').html('<div>
foo
</div>');
$('#搜索结果').html('
福
');

如果HTML是局部的,为什么不首先将其呈现在正确的位置,而是为其样式设置
display:none
,然后在需要时使用jQuery显示元素?

感谢您解释JS为什么这样做。我不能事先渲染元素。我想做的是让一个搜索表单在一个div中显示它的结果。我记得在Rails 1(上次我使用Rails)中,这是一件非常琐碎的事情但是我在Rails 4中似乎找不到类似的简单方法,我已经使用.gsub解决了这个问题,并在问题的末尾发布了这个问题。@Axiombadger如果您正在呈现来自ajax查询的响应,那么您可以使用jQuery的
load
函数,避免使用
html
手动显示结果功能。e、 g.
$('#某些div id')。加载('http://url.to/get/the/data“)
调用返回的HTML将直接呈现到指定的元素中。谢谢@neuronaut。我想我必须通过它发送GET参数,而不是发布表单?@Axiombadger不一定——根据jQuery文档:“如果数据作为对象提供,则使用POST方法;否则,假定使用GET。”您使用哪种方法更符合服务器端的期望,但不管怎样,我认为您都必须从表单字段中读取2个值,以设置对
load
的调用。有关更多详细信息,请参阅。
$('#search_results').html('<div>
foo
</div>');