gpt4 book ai didi

javascript - 如何更新响应式前端和数据库?

转载 作者:行者123 更新时间:2023-12-02 23:53:03 24 4
gpt4 key购买 nike

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

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

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

它工作得很好,但数据库此时当然没有更新。

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

最佳答案

您的 updateQuantity() 函数必须对 Controller 中的方法进行 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 清理 Controller 中的输入.

在你的 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

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

# => 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 部分。

关于javascript - 如何更新响应式前端和数据库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55557973/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com