簡體   English   中英

Escape_javascript問題

[英]Escape_javascript problem

我的用戶/編輯頁面上有一組相關的下拉菜單。 用戶選擇父下拉菜單,然后限制子下拉菜單中可用的選擇。 用戶可以添加多組父/子下拉列表。 產品是父母。 多樣性是孩子。

除非將包含雙引號的各種形式輸入數據庫,否則這一切都很好。 發生這種情況時,它會中斷javascript,並且渲染部分代碼的觸發器根本不起作用。

單引號不會引起此問題,我嘗試過的任何其他字符也不會引起此問題。 因此,此問題特定於雙引號。 我以為escape_javascript是這里的答案,但是我嘗試將其放在代碼中的許多不同位置,但沒有任何效果。 我很可能不確切知道助手和括號的位置。

api文檔很糟糕。 它說的是escape_javascript()。 那對我沒有幫助。 同樣,在線也沒有很多明確的指導。 我已經搜索了幾個小時。

這是我的代碼的相關部分:

Users#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]);
    }
  });
}

假設您只是在做一些轉義錯誤(並且rails正確執行了此操作),則可以嘗試執行以下操作:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM