我使用Python cherrypy
和Jinja
來爲我的網頁提供服務。我有兩個Python文件:Main.py(處理網頁)和search.py(服務器端函數)。
我創建一個基於本地JSON
文件名爲component.json(按功能componentSelectBar內search.py創建)(使用JavaScript
)動態下拉列表。如何將Python創建的JSON數據發送到JavaScript?
我想問一下怎麼能我的JavaScript檢索JSON數據沒有JSON數據物理存儲到我的本地網站根目錄的文件夾,仍然實現動態下拉列表的功能。
的componentSelectBar函數內部search.py:
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,就是這樣。 您的問題目前包含太多的信息,這與問題無關。請考慮減小它的大小,並提供最少量的代碼,以免使讀者感到困惑。 – webKnjaZ