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



我正在寻找更新玩具电子商务应用程序中购物车的方法,而无需重新加载页面,我正在关注这支笔。

例如,更新产品数量的代码如下:

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

它运行良好,但此时数据库当然没有更新。

我想知道使用产品数量或类似操作更新前端和数据库的最佳方法是什么?我可能正在寻找 AJAX,但不确定最新的最佳实践是什么(理想情况下使用尽可能少的 JS(。

您的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
    }
  });
}

我建议将要更新的产品的 ID 附加到输入的父级,以便您可以将其传递到路由,并记住在所需范围内传递值,以便您可以通过 strong_params 清理控制器中的输入。

在控制器中:

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

如果您决定使用 js 而不是 json 进行响应,则需要创建一个与方法同名的视图,扩展名为 .js或 .js.erb(而不是 .html/.html.erb(,并在 js 中处理成功的响应。在此视图中,您可以访问方法中声明的所有实例变量。例如:

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

如果采用此路由,请记住删除 ajax 调用的success部分。

最新更新