简体   繁体   English

如何同时更新响应式前端和数据库?

[英]How to update both a responsive front-end and the database?

I am looking for ways to update the cart in my toy e-commerce application without having to reload the page and I was following this pen. 我正在寻找无需重新加载页面即可更新玩具电子商务应用程序中购物车的方法,而我一直在关注这支笔。

For example the code that is updating a product's quantity is the following: 例如,更新产品数量的代码如下:

$('.product-quantity input').change( function() {
  updateQuantity(this);
});

It works nicely but the database is not updating of course at this point. 它工作得很好,但是数据库目前还没有更新。

I was wondering what is the best way to update both the front-end and the database with products' quantities or similar operations? 我想知道用产品数量或类似操作更新前端和数据库的最佳方法是什么? I am probably looking for AJAX but not sure what the latest best practices are (ideally with as less JS as possible). 我可能正在寻找AJAX,但不确定最新的最佳做法是什么(最好使用尽可能少的JS)。

Your updateQuantity() function has to make an ajax call to a method in your controller that handles the change in the database and responds to either json or js to manipulate the dom. 您的updateQuantity()函数必须对控制器中的方法进行ajax调用,该方法处理数据库中的更改并响应json或js以操纵dom。

function updateCart(e){
  $.ajax({
    type: "patch",
    url: 'your_route_to_method', //point to the route that updates the item
    data: {
      your_resource_scope: { quantity: e.value } //sanitize input in strong params
    },
    success: function (response) {
      //response is the json you get back from your controller
      //handle the logic of whatever happens in the dom after you update the quantity
    }
  });
}

I'd suggest attaching the id of the product you want to update to the input's parent so you can pass it to your route and remember to pass the value under the required scope so you can sanitize the input in your controller via strong_params. 我建议将要更新的产品的ID附加到输入的父级,以便可以将其传递到路由,并记住在所需范围内传递值,以便可以通过strong_params在控制器中清除输入。

In your controller: 在您的控制器中:

def update
  respond_to do |format|
  if @your_resource.update(your_resource_params)
    format.json { render json: { key: value } } #build the json you want to return
  else
    #handle failiure
  end
end

If you decide to respond in js instead of json, you need to create a view with the same name as your method with a .js or .js.erb extension (instead of .html/.html.erb) and handle the successful response in js. 如果您决定使用js而不是json进行响应,则需要创建一个与您的方法名称相同的视图,并带有.js或.js.erb扩展名(而不是.html / .html.erb),并处理成功的响应在js中。 In this view you have access to all the instance variables declared in your method. 在此视图中,您可以访问在方法中声明的所有实例变量。 For example: 例如:

# => update.js.erb or your_custom_method_name.js.erb
$('#resource_#{ @your_resource.id }_price').replaceWith('<p>#{ @your_resource.quantity * @your_resource.price }</p>');

If you go this route, remember to delete the success part of your ajax call. 如果走这条路,请记住删除ajax调用的success部分。

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

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