2011-04-09 66 views
2

我想通过AJAX将图像src发送给浏览器。如何将密钥发送给JavaScript?

服务器端:

que = db.Query(Imageitem).order('-created') 
item_list = que.fetch(limit=1) 
if(len(item_list)>0): 
    itemkey = {'imgid':item_list[0].key()} 
else: 
    itemkey = {'imgid':''} 
json_itemkey = gaejsonEncoder.encode(itemkey) 

客户端模板:

<img src='img?img_id=$(.imgid)'></img> 

我用SNBinder用于客户端绑定和$指的ItemKey [0] .imgid(imgid)。

但这是错误的。

datastore_types.Key.from_path(u'Imageitem', 515L, _app=u'fileshare') 
is not JSON serializable 

有什么办法将数据存储实体的密钥发送到客户端?

任何建议非常感谢。

回答

2

如果你想JSON编码的关键项目,只需要使用钥匙串版本通过将关键STR():

itemkey = {'imgid': str(item_list[0].key())} 
+0

谢谢。有什么办法将字符串转换为键? – 2011-04-09 13:52:38

+0

很确定所有期望Key对象[也接受字符串](http://code.google.com/appengine/docs/python/datastore/modelclass.html#Model_get)版本的方法。 – 2011-04-09 13:56:24

+0

imgitem = db.get(self.request.get(“img_id”))。这是错误; BadKeyError:无效的字符串键undefined ===。我如何使用“img_id”?抱歉。 – 2011-04-09 14:03:38

0

林我来说,我并不需要的关键,所以我使用从json.JSONEncoder扩展的类来捕获所述db.Model的Key实例。

import json 
from datetime import datetime 
from google.appengine.ext.db import Key 

class ComplexEncoder(json.JSONEncoder): 
    def default(self,obj): 
     if isinstance(obj,datetime): 
      return obj.isoformat() 
     if isinstance(obj,Key): 
      return '' 
     return json.JSONEncoder.default(self,obj)