简体   繁体   English

Web2Py中的ajax和会话变量问题

[英]Problems with ajax and session variable in Web2Py

I'm developing an app in Web2Py that consists in a little e-commerce. 我正在Web2Py中开发一个包含一些电子商务的应用程序。 Have a controller and page that the link is localhost:8000/topranchos/produto, with products, were topranchos is the app. 有一个控制器和页面,该链接是localhost:8000 / topranchos / produto,以及产品,其中topranchos是应用程序。

In the page produto there are a list of products like this: 在produto页面中,有这样的产品列表:

The image is in this link 图片在此链接中

When the button "Adicionar ao carrinho" is clicked, the javascript function is executed: 单击按钮“ Adicionar ao carrinho”时,将执行javascript函数:

<script>
    function adicionarCarrinho(prod, qtde) {
        quantidade = document.querySelector(qtde).value
        console.log(quantidade)
      if(quantidade > 0) {
          $.get("{{=URL(f="adicionarCarrinho")}}", {produto: prod, qtde: quantidade} )
            .done(function( data ) {
                console.log (data)
                var atual =document.querySelector(".badge-carrinho").innerHTML;
                document.querySelector(".badge-carrinho").innerHTML =
                parseInt(quantidade) + parseInt(atual);
                alert("Adicionado ao carrinho com sucesso");
                });
        }
        else alert("Selecione a quantidade de itens deste produto que você deseja");
    }
</script>

It's make a requisition to the action default/adicionarCarrinho: 这是对动作default / adicionarCarrinho的要求:

def adicionarCarrinho():
if request.vars:
    session.carrinho.append(
    #{'produto':db(db.produto.id == request.vars['produto']).select(),
    {'produto':int(request.vars['produto']),
    'quantidade':int(request.vars['qtde'])}
    )
    print "----------"
    print session.carrinho
    return str("OK")

Where session.carrinho have a list that was declared on db.py model: 其中session.carrinho具有在db.py模型上声明的列表:

#carrinho
session.carrinho = []

On the terminal, the command print session.carrinho print the item received by the ajax request, but when I add other itens the list is empty. 在终端上,命令print session.carrinho命令打印ajax请求收到的项目,但是当我添加其他项目时,列表为空。 When I click on the page of carrinho, that shows the session.carrinho's informations, the var is empty. 当我单击carrinho的页面时,该页面显示了session.carrinho的信息,该变量为空。

How can I repair this? 我该如何修理? I tried use cookies of course Web2Py book, but I dummie on Web2Py and not has success yet :/ 我试过使用Web2Py书中的cookie,但是我在Web2Py上傻了傻,但还没有成功:/

thank you! 谢谢!

The model file is executed on every request, so you are resetting session.carrinho back to an empty list on every request. 模型文件将在每个请求上执行,因此您需要将session.carrinho重置为每个请求的空列表。 Instead, in the model, this: 相反,在模型中,这是:

session.carrinho = []

should be something like: 应该是这样的:

session.carrinho = [] if session.carrinho is None else session.carrinho

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

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