我有一个在线商店,它使用本地存储来跟踪购物车中有哪些产品(像cart = [{"id":"1"},{"id":"2"},{"id":"4"}]
一样存储)。当用户导航到cart.html时,我希望将cart
发送到我的后端,生成一个完整的产品列表,然后在return render_template
调用中使用该列表。
后端可以很好地接收cart
,并且可以毫无问题地生成列表,但是我无法将列表发送到cart.html页面(看起来好像cart
是空的)。POST请求应该不在cart.html上,而是用重定向来解决它吗?如果是这样,我该怎么做呢?如果可能的话,我希望避免在cart.html上有一个“加载购物车”按钮。
这是cart.html的开始(我尝试将ajax调用设置为async: false,但这并没有阻止页面在没有cart
的情况下呈现
{% extends "layout.html" %}
{% block content %}
<script type="text/javascript">
function sendCart() {
$(document).ready(function() {
$.ajax({
url: "{{ url_for('cart', _external=True) }}",
type: 'POST',
data: JSON.stringify(JSON.parse(localStorage.getItem("cart"))),
contentType: "application/json; charset=utf-8",
dataType: "json",
});
})
}
sendCart();
</script>
...
这是我的路线:
@app.route('/cart', methods=['GET', 'POST'])
@login_required
def cart():
cart = []
if request.method == 'POST':
for i in request.json:
cart.append(get_Furniture(int(i['id'])))
return render_template("cart.html", cart_objects = cart)
return render_template("cart.html", cart_objects = cart)
编辑:已解决
我发现跳过使用ajax和本地存储更容易,而不是使用易于在后端访问的cookie :不需要请求,我可以在呈现页面之前生成cart
。
发布于 2020-04-22 19:15:51
我发现跳过使用ajax和本地存储更容易,而不是使用易于在后端访问的cookie :不需要请求,我可以在呈现页面之前生成购物车。
https://stackoverflow.com/questions/61345943
复制相似问题