javascript - 如何将Python创建的JSON数据发送到JavaScript?

标签 javascript python html json cherrypy

我正在使用 Python cherrypyJinja 来服务我的网页。我有两个 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>");
        });
    });

最佳答案

  1. 将 componentSelectBar 的结果存储到数据库中
  2. 公开新的 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/

相关文章:

javascript - 使异步调用同步

python - 我们可以在spyder中直接使用One Hot Encoding而不使用标签编码来处理分类数据吗

javascript - 获取没有 id 的元素的值

javascript - 更改事件目标

javascript - 检查同一数字是否连续随机两次

javascript - clearText 函数中的 'e' 参数是什么意思?

python - 对象用作 "self"参数?

python - 以随机顺序制作 HTML 表单

javascript - attr.ownerElement 是什么意思?

python - Pandas ,适用于作为数据框行条目的参数