【问题标题】:Why does this Web2Py ajax call fail to return the value of a variable?为什么这个 Web2Py ajax 调用无法返回变量的值?
【发布时间】:2016-01-20 08:16:38
【问题描述】:

这是我的 Web2Py 视图中的相关 sn-p:

{{for candidate in rows:}}
    <div class="well col-sm-12">
        <button type="button" name="up_button" onclick="ajax('{{=URL('default', 'arrow_button_callback')}}', ['name'], 'target')" class="fa fa-caret-up arrow-up fa-4x"></button>
        <span>{{=candidate.votes}}</span>
        <button type="button" name="down_button" onclick="ajax('{{=URL('default', 'arrow_button_callback')}}', ['name'], 'target')" class="fa fa-caret-down arrow-down fa-4x"></button>
        {{=IMG(_src=URL('photos',candidate.path_to_photo), _alt="Photo of Candidate")}}
        {{=candidate.name}}
        <div id="target"></div>
   </div>
{{pass}}

以及来自我的 Web2Py 控制器的相关 sn-p:

def arrow_button_callback():
    response.flash = str(request.post_vars.name)
    return request.post_vars.name

那么为什么我会在我的目标 div(和我的 flash)中看到字符串“None”?

感谢您的帮助。我阅读了 Web2Py 书的第 11 章,但我仍然感到困惑。

我真的希望能够将candidate.id(取决于按下哪一行的按钮)和按钮方向传递给控制器​​变量。如果有更好的方法,请告诉我。

--本杰明

【问题讨论】:

    标签: ajax web2py


    【解决方案1】:

    来自 web2py 文档(已添加重点):

    ajax(url, [name1, name2, ...], target)

    它异步调用 url(第一个参数),传递 字段输入 的值,其名称等于列表中的一个名称(第二个参数) ...

    在您的代码中,您的第二个参数是['name']。但是,任何地方都没有名称为“name”的输入字段,因此没有“name”变量被发布到 web2py(因此,request.post_vars.nameNone,这是每当您尝试获取一个变量时返回的默认值在request.post_vars 中不存在)。

    在这种情况下,由于您没有在表单输入字段中放置任何数据,您可以简单地忽略 ajax() 的第二个参数。相反,通过 URL 本身传递相关数据:

       {{url = URL('default', 'arrow_button_callback',
                   vars=dict(id=candidate.id, direction='up'))}}
       <button type="button" name="up_button" onclick="ajax('{{=url}}', [], 'target')"
        class="fa fa-caret-up arrow-up fa-4x"></button>
    

    然后在arrow_button_callback 控制器中,您可以通过request.get_vars.id(或只是request.vars.id)访问候选ID。您可以通过request.vars.direction 访问箭头方向。为“向下”按钮创建一个新 URL,使用 direction='down'

    【讨论】:

    • 谢谢!我能够通过candidate.id。我只需要在变量声明的末尾添加两个花括号。现在我只是对如何发送单击的按钮方向感到困惑......
    • 糟糕,刚刚修好了。至于传达按钮方向,只需将其添加到 URL 查询字符串中(请参阅我更新的答案)。
    猜你喜欢
    • 2021-12-09
    • 1970-01-01
    • 1970-01-01
    • 2013-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-17
    相关资源
    最近更新 更多