【发布时间】:2017-01-27 23:31:58
【问题描述】:
我正在使用 Python cherrypy 和 Jinja 为我的网页提供服务。我有两个 Python 文件:Main.py(处理网页)和 search.py(服务器端函数)。
我基于名为 component.json 的本地 JSON 文件创建了一个动态下拉列表(使用 JavaScript)(由 search.py 中的函数 componentSelectBar 创建)。
我想问一下,我的 JavaScript 如何在不将 JSON 数据物理存储到我本地网站根文件夹中的情况下检索 JSON 数据,并且仍然可以实现动态下拉列表的功能。
search.py中的componentSelectBar函数:
def componentSelectBar(self, brand, category):
args = [brand, category]
self.myCursor.callproc('findComponent', args)
for result in self.myCursor.stored_results():
component = result.fetchall()
if (len(component) == 0):
print "component not found"
return "no"
components = []
for com in component:
t = unicodedata.normalize('NFKD', com[0]).encode('ascii', 'ignore')
components.append(t)
j = json.dumps(components)
rowarraysFile = 'public/json/component.json'
f = open(rowarraysFile, 'w')
print >> f, j
print "finish component bar"
return "ok"
selectBar.js:
$.getJSON("static/json/component.json", function (result) {
console.log("retrieve component list");
console.log("where am i");
$.each(result, function (i, word) {
$("#component").append("<option>"+word+"</option>");
});
});
【问题讨论】:
-
基本上,你需要一个处理程序来标记@cherrypy.tools.json_out 装饰器返回字典/列表。只需在 JS 中更改 URL,就可以了。您的问题当前包含太多信息,看起来与问题无关。请考虑减小其大小并仅提供最少量的代码,以免使读者感到困惑。
标签: javascript python html json cherrypy