【问题标题】:How to render JSON on client-side from Google App Engine Entity如何从 Google App Engine 实体在客户端呈现 JSON
【发布时间】:2015-10-30 22:07:14
【问题描述】:

非常感谢在客户端从 Google App Engine 实体呈现 JSON 对象的帮助。

这是我所有的相关代码:

def render_str(template, **params):
   t = jinja_env.get_template(template)
   return t.render(params)

class BlogHandler(webapp2.RequestHandler):
   def write(self, *a, **kw):
      self.response.out.write(*a, **kw)

   def render_str(self, template, **params):
      params['user'] = self.user
      return render_str(template, **params)

   def render(self, template, **kw):
      self.write(self.render_str(template, **kw))

class Post(ndb.Model):
   subject = ndb.TextProperty(required = True)
   created = ndb.DateTimeProperty(auto_now_add = True)
   startdate = ndb.DateTimeProperty()
   enddate = ndb.DateTimeProperty()

class PostPage(BlogHandler):
    def get(self, post_id):
    key = ndb.Key('Post', int(post_id), parent=blog_key())
    post = key.get()
    postdict = post.to_dict()
    postdict['startdate'] = postdict['startdate'].isoformat()
    self.render("permalink.html", postdict = postdict)

在模板页面的脚本标签中,我包含

<script>
var jsonobject = JSON.parse({{ postdict['startdate']}});
var jsonobject1 = new Date(jsonobject);
</script>    

我在正确的轨道上吗?我想最终将客户端上的 datetime 对象用于一些 Jquery 函数。

任何帮助我指出正确的方向将不胜感激。

【问题讨论】:

  • 您在应用引擎端使用什么语言编写?并且您是否将对象转储到 Web 浏览器端? console.log(...) 播放负载?
  • 非常感谢您的回复。我在应用引擎端使用python。我没有在网络浏览器端转储对象。你能告诉我怎么做吗?

标签: python json google-app-engine jinja2


【解决方案1】:

您的代码存在许多问题。首先,一旦将post 转换为字典postdict,就不能使用点符号引用元素。您必须使用字典引用 postdict['startdate'] 来引用 startdate 元素。

接下来,我在以 JSON 格式存储日期时使用isoformat() 函数:

postdict['startdate'] = postdict['startdate'].isoformat()

这使得转换为 Javascript Date 对象变得更加容易:

<script>
var jsonobject = JSON.parse({{ postdict.jsonobject}});
jsonobject[0].y = new Date(jsonobject[0].y);
</script>

【讨论】:

  • 非常感谢您的回复。我现在有以下代码:postdict = post.to_dict()x = postdict['startdate'].isoformat()y = [ {'y':x} ]jsonobject = json.dumps(y)postict['jsonobject'] = jsonobject 在这个模板的脚本标签中,我有:var jsonobject = JSON.parse( {{ postdict['jsonobject'] }} );jsonobject[0].y = new Date(jsonobject[0].y); 但是,当我引用变量 jsonobject[0 ].y 在 jQuery 函数中,我在控制台中收到一个错误,即 jsonobject 未定义且 JSON.parse 需要至少 1 个参数。
  • 你是如何渲染你的模板的? template.render(postdict)?
  • 我使用以下函数:def write(self, *a, **kw): self.response.out.write(*a, **kw)def render_str(self, template, **params): return render_str(template, **params)def render(self, template, **kw): self.write(self.render_str(template, **kw))
  • 请使用所有代码更新您的问题,包括使用postdict 调用。
  • 谢谢 我现在已经包含了所有的代码。我非常感谢您的帮助。我是编程新手,很难理解如何在客户端获取我的实体的 datetime 属性,以便可以在 jQuery 函数中使用它。
猜你喜欢
  • 1970-01-01
  • 2014-05-07
  • 1970-01-01
  • 1970-01-01
  • 2013-11-05
  • 2013-10-21
  • 1970-01-01
  • 1970-01-01
  • 2019-03-08
相关资源
最近更新 更多