我正在使用 Python cherrypy
和 Jinja
来服务我的网页。我有两个 Python 文件:Main.py(处理网页)和 search.py(服务器端函数)。
我基于名为 component.json 的本地 JSON
文件(由函数 componentSelectBar< 创建)创建一个动态下拉列表(使用 JavaScript
)/em> search.py 内)。
我想问一下,我的 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>");
});
});
最佳答案
- 将 componentSelectBar 的结果存储到数据库中
- 公开新的 API 以从数据库获取结果并将 json 返回到浏览器
演示在这里:
@cherrypy.expose
def codeSearch(self, modelNumber, category, brand):
...
result = self.search.componentSelectBar(cherrypy.session['brand'], cherrypy.session['category'])
# here store result into a database, for example, brand_category_search_result
...
@cherrypy.expose
@cherrypy.tools.json_out()
def getSearchResult(self, category, brand):
# load json from that database, here is brand_category_search_result
a_json = loadSearchResult(category, brand)
return a_json
关于 CherryPy 的文档,希望有帮助: Encoding response
在你的浏览器中,你需要 GET/getSearchResult 获取 json:
$.getJSON("/getSearchResult/<arguments here>", function (result) {
console.log("retrieve component list");
console.log("where am i");
$.each(result, function (i, word) {
$("#component").append("<option>"+word+"</option>");
});
});
关于javascript - 如何将Python创建的JSON数据发送到JavaScript?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39587355/