难以将快速会话变量实现为数组 [英] Stumped implementing express-session variables as an array
问题描述
试着在这里试图表达。我正在使用快速会话模块,当我使用对象或字符串的会话变量时,我没有遇到任何麻烦。但是,我似乎无法让数组工作。我正在使用购物车技术作为实验室老鼠。以下是导致我出现问题的代码:
Trying to grok Express here. I'm using the express-session module and I've had no trouble when I'm using session variables that are objects or strings. However, I just can't seem to get arrays to work. I'm using the shopping cart technique as a lab rat. Here's the code that's causing me problems:
router.post('/', function(req, res) {
if (req.body.action == 'Add to Cart') {
var cart = req.session.cart = [];
cart.push(req.body.itemId);
res.redirect('/');
}
});
router.get('/', function(req, res) {
if (req.session.cart) {
var itemsInCart = req.session.cart.length;
}
res.render('index', {
title: 'Shopping Spree',
itemsInCart: itemsInCart,
products: [
{id: 1, item: 'Boeing 747', price: 4500},
{id: 2, item: 'Luxury Yacht', price: 200},
{id: 3, item: 'Mercedes AMG GT', price: 15000},
{id: 4, item: 'Apple iPhone 6', price: 2400},
{id: 5, item: 'Moet Hennessey', price: 5000}
]
});
});
在视图中: index.jade
:
extends layout
block content
h2= title
p Cart(#{itemsInCart} items)
a(href="/cart") [VIEW CART]
table
thead
tr
th Item
th Price
tr
tbody
- for (var i in products) {
tr
td= products[i].item
td= products[i].price
td
form(action="/", method="post")
input(type="hidden", name="itemId" value="#{products[i].id}")
input(type="submit", name="action", value="Add to Cart")
- }
第一次点击添加到购物车按钮时, itemsInCart
确实更新为1.后续添加到购物车的点击次数无法启动约会价值。
The first time the 'Add to Cart' button is clicked, itemsInCart
is indeed updated to 1. Subsequent 'Add to Cart' clicks won't update that value.
请指教。
推荐答案
使用此行
var cart = req.session.cart = [];
每次调用它时,都会将req.session.cart的内容重新定义为[]。
each time you call it, you redefine content of req.session.cart to [].
请改为:
var cart = req.session.cart || [];
它将保留 cart
的现有值,并且你不会放弃以前的项目
It will keep existing value of cart
and you will not loose previous items
更新
至于更新的问题,这里是你可以做的,保持Jade的绑定更新:
As for updated question, here is what you can do, to keep Jade's bindings updated:
var pageScope;
router.post('/', function (req, res) {
if (req.body.action == 'Add to Cart') {
var cart = req.session.cart = [];
cart.push(req.body.itemId);
pageScope.itemsInCart = req.session.cart && req.session.cart;
res.redirect('/');
}
});
router.get('/', function (req, res) {
pageScope.itemsInCart = req.session.cart && req.session.cart;
res.render('index', pageScope = {
//...
});
});
想法是每次更新 itemsInCart
,你增加 cart
数组的长度。
Idea is to update itemsInCart
, every time, you increase the length of cart
array.
这篇关于难以将快速会话变量实现为数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!