0

我在文件 dvbd.js.erb 中有这个,它工作正常。预期的行为是 Dave div 将在其中列出一组名称和 id。

<%@dimvers = DimensionVersion.select("name, id").where(:dimension_id => params[:id]).all %>


$("#dave").html("<%= @dimvers.collect { |d| [d.name, d.id]} %>");

这是在 applications.js 中,并且 .post 调用 dvbd.js.erb 很好:

jQuery.ajaxSetup({
  'beforeSend': function(xhr) { xhr.setRequestHeader("Accept", "text/javascript") }
});

$.fn.subSelectWithAjax = function() {
  var that = this;

  this.change(function() {
    $.post("/dimensions/dvbd", {id: that.val()}, null, "script");
  });
}

$(document).ready(function(){
$("#dimver_dimension_id").subSelectWithAjax();
});

但是,当我将 dvbd.js.erb 中的代码更改为以下代码时,它不起作用。我希望它能够更改选择框#dimension_id 的选项。但是,如果@dimvers 碰巧没有返回匹配的记录,它只会将选择框更改为没有内容/选项。然后#dimension_id 不再响应。

<%@dimvers = DimensionVersion.select("name, id").where(:dimension_id => params[:id]).all %>

$("#dimension_id").html("<%= options_for_select(@dimvers.collect {|d| [d.name, d.id] }).gsub(/n/, '') %>");

这是 show.html.erb 中的代码:

<div id = 'hierarchypanel'>
    <%= collection_select(:dimver, :dimension_id, Dimension.all, :id, :title ) %>
    <%= collection_select(:dimension,:id, @dimension_versions,:id, :name)  %>
</div>
4

2 回答 2

1

尝试将html传递给escape_javascript

$("#dimension_id").html("<%= escape_javascript options_for_select(@dimvers.collect { |d| [d.name, d.id] }) %>");

于 2013-02-04T06:11:44.603 回答
0

最好的方法是有一个partial并在partial中有select_tag,然后从你的.js.erb中调用那个partial

前任:

#_select_partial.erb
<%= options_for_select(@dimvers.collect {|d| [d.name, d.id] }).gsub(/n/, '') %>

#dvbd.js.erb
$("#dave").html("<%= raw escape_javascript(render(:partial => 'select_partial')) %>")
于 2013-02-04T06:05:21.237 回答