简体   繁体   English

如何在 Rails 中实现 AJAX 价格比较功能?

[英]How to implement an AJAX price compare feature in Rails?

I want to create an AJAX price compare feature.我想创建一个 AJAX 价格比较功能。 I don't really know how it should work.我真的不知道它应该如何工作。

A user should be able to select a company and a loading icon will appear.用户应该能够 select 一个公司,并且会出现一个加载图标。 The list of companies will be ordered by price and show how much the user can save.公司列表将按价格排序,并显示用户可以节省多少。

Here is my form:这是我的表格:

<select style=" margin-left:10px;width:370px;float: left;
    margin-top: 10px;"name="konkurrancer[form]" id="konkurrancer_form" class="select optional">
<option value="Andet">Company 1</option>
<option value="Andet">Company 2</option>
<option value="Andet">Company 3</option>
</select>

And I have a table with all the company names and prices.我有一张包含所有公司名称和价格的表格。

My table:我的桌子:

name    price   id
comany 1    120 1
comany 2    80  2
comany 3    60  3
comany 4    40  4

Example: A user selects company 1, that has the price $120.示例:用户选择价格为 120 美元的公司 1。 He will see all the companies ordered and determine how much he can save.他将查看所有订购的公司并确定他可以节省多少。 In this case, he would see company 4 first and the information that he can save (120-40) 80$.在这种情况下,他会首先看到公司 4 以及他可以节省 (120-40) 80 美元的信息。

  1. add a route to config/routes.rb to support your new controller action.添加路由到 config/routes.rb 以支持您的新 controller 操作。
  2. add the javascript that fires off the ajax添加启动 ajax 的 javascript
  3. add the action handler to your controller将动作处理程序添加到您的 controller
  4. insert your above described business logic插入上述业务逻辑
  5. return your data using the json version of render使用 json 版本的渲染返回您的数据
  6. handle the return data on the javascript side.在 javascript 端处理返回数据。

I think if you use something like jQuery, a lot of this becomes easier because it appears you'll want to do some basic DOM manipulation as a part of (6).我认为如果你使用 jQuery 之类的东西,这会变得更容易,因为看起来你会想要做一些基本的 DOM 操作作为 (6) 的一部分。

I can't really help you sort out the algorithm in (4) but I can answer more directed questions about the other steps if you have any.我真的无法帮助您理清(4)中的算法,但如果您有任何其他步骤,我可以回答更多有针对性的问题。

Edit: Sort the companies by price, low to high, then when you subtract the current price from each one you'll end up with the greatest savings first.编辑:按价格从低到高对公司进行排序,然后当您从每个公司中减去当前价格时,您将首先获得最大的节省。

As for your controller, I guess you'll need to pass in the current price, and the id of the company selected...至于你的 controller,我想你需要传入当前价格,以及所选公司的 id ......

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

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