简体   繁体   English

HAML中的Javascript中的Javascript

[英]Javascript in HAML in Javascript

I've got a question that mightve been asked before but i have trouble finding a proper description. 我有一个以前可能已经问过的问题,但是我找不到合适的描述。 I hope someone can help me out. 我希望有人能帮助我。

In the code below on the line where i set var price i want to add the javascript variable accu_id to find a record in my DB through rails. 在下面我在其中设置var price的行上的代码中,我想添加javascript变量accu_id以通过rails在我的数据库中找到一条记录。 How do I do this in embedded rails in javascript? 如何在javascript的嵌入式Rails中做到这一点?

 :javascript
    $('#accu').change(function() {
      var accu_id = $("#accu")[0].selectedOptions[0].value
      var price = "#{currency(Product.find_by(id: accu_id).price2)}"
      $('#price_accu').append(price)
    });

Or is there an easier way to do this? 还是有更简单的方法来做到这一点?

You have two options. 您有两个选择。

  1. You can use AJAX request to get data from database 您可以使用AJAX请求从数据库获取数据
  2. You can use mapping concept like following 您可以使用如下的映射概念

    var data = @processed_data // json data, which contains processed data in json format. var data = @processed_data // json数据,其中包含json格式的已处理数据。
    var accu_id = $("#accu")[0].selectedOptions[0].value var accu_id = $(“#accu”)[0] .selectedOptions [0] .value
    var price = data.accu_id; var price = data.accu_id;

Here the @processed_data contains data like following 这里@processed_data包含如下数据

@processed_data = currency_calculation

def currency_calculation
   Product.all.map { |product| [product.id, currency(product.price2) ] }.as_json 
end

Example

Assume products table have two entries then the @processed_data contain values like following 假设产品表有两个条目,则@processed_data包含如下值

{ "1" => "20.00", "2" => "25.50" }

The above data directly assigned to js variable data and accessed like data.key 上面的数据直接分配给js变量数据,并像data.key一样访问

The first option is best choice and second is possible one. 第一个选择是最佳选择,第二个是可能的选择。

Note : You can't use js variable inside ruby. 注意 :您不能在ruby中使用js变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM