【问题标题】:Escape_javascript problemEscape_javascript 问题
【发布时间】:2009-11-14 07:05:41
【问题描述】:

我的用户/编辑页面上有一组相关的下拉菜单。用户选择父下拉列表,然后限制子下拉列表中可用的选择。用户可以添加多组额外的父/子下拉列表。产品是父级。品种是孩子。

除非将包含双引号的品种输入到数据库中,否则这一切都很好。发生这种情况时,它会破坏 javascript,并且渲染部分的触发器根本不起作用。

单引号不会导致此问题,我尝试过的任何其他字符也不会。所以这个问题是特定于双引号的。我认为 escape_javascript 是这里的答案,但我尝试将它放在代码中的许多不同位置,但没有任何效果。很可能我只是不知道助手和括号应该去哪里。

api 文档很糟糕。它说escape_javascript()。这对我没有帮助。同样,网上也没有太多明确的指导。我已经搜索了几个小时。

以下是我的代码的相关部分:

用户#edit.html.erb

<%= render :partial => 'season', :collection => @user.seasons %>

用户#_season.html.erb

<% fields_for prefix, season do |season_form| -%>
  <%= error_messages_for :season, :object => season %>
    Product: <%= season_form.collection_select :product_id, Product.find(:all, :order =>'name'), :id, :name, {:prompt => "Select Product"}, {:onchange => "collectionSelected(this);"} %>

    <% varieties = season.product ? season.product.varieties : Variety.all %>
    <%= season_form.select :variety_id, options_from_collection_for_select(varieties, :id, :name, season.variety_id), :prompt => "This is optional" %>    

Javascripts#dynamic_varieties.js.erb

var varieties = new Array();
<% for variety in @varieties -%>
  varieties.push (new Array (<%=h variety.product_id %>, "<%=h variety.name %>", <%=h variety.id %>));
<% end -%>


function collectionSelected(e) {
  product_id = e.getValue();
  options = e.next(1).options;
  options.length = 1;
  varieties.each(function(variety) {
    if (variety[0] == product_id) {
      options[options.length] = new Option(variety[1], variety[2]);
    }
  });
}

【问题讨论】:

    标签: javascript ruby-on-rails


    【解决方案1】:

    假设您只是在做一些错误的转义(并且 rails 是正确的),您可以尝试以下操作:

    var varieties = <%= @varieties.map { |v| [v.product_id, h(v.name), v.id] }.to_json %>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多