【问题标题】:How can I access items within a ndb query object clientside?如何访问 ndb 查询对象客户端中的项目?
【发布时间】:2012-07-03 07:13:15
【问题描述】:

我正在使用 appengine、django 和 webapp2,并且正在发送一个查询对象客户端,这样

{{ exercise_steps }}

返回

Query(kind='ExStep')

{{ exercise_steps.count }}

返回 4

我正在尝试将变量 exercise_steps 放入一些 javascript 代码中,并且需要遍历 javascript(不是 django)循环中的项目,但我似乎无法访问这些项目。

我试过 {{ exercise_steps|0 }}, {{ exercise_steps[0] }}, {{ exercise_steps.0 }} 但它什么也没返回。我知道我可以使用 django 循环来做到这一点,但是有没有一种方法可以使用类似

的方法通过 javascript 循环访问查询中的对象
for (var i = 0; i < {{exercise_steps.count}}; i++) {
    console.log({{ exercise_steps.i.location }})
}

【问题讨论】:

    标签: django google-app-engine webapp2


    【解决方案1】:

    您不能混合使用客户端代码和模板代码...当 javascript 运行时,您的 python 代码已经执行。您没有将 python 对象发送到 javascript - 它是在生成 HTML 时执行的。

    你需要在JS中重新创建数组,或者让ajax调用从python返回一个数组。

    var steps = [
        {% for step in exercise_steps %}
             {{ step.location }}{% if not forloop.last %},{% endif %}
        {% endfor %}]; // now your python iterable is a JS array.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-12-16
      • 1970-01-01
      • 2021-10-14
      • 1970-01-01
      • 2020-03-28
      • 1970-01-01
      • 1970-01-01
      • 2014-09-02
      相关资源
      最近更新 更多