【问题标题】:How to send JSON data created by Python to JavaScript?如何将 Python 创建的 JSON 数据发送到 JavaScript?
【发布时间】:2017-01-27 23:31:58
【问题描述】:

我正在使用 Python cherrypyJinja 为我的网页提供服务。我有两个 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


【解决方案1】:
  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 for 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>");
    });
});

【讨论】:

    【解决方案2】:

    要将 json 数据直接用于 javascript,您可以使用

    var response = JSON.parse(component);
    console.log(component); //prints
    

    您已经创建了 json 文件。如果该文件格式正确,那么您可以使用 jQuery jQuery.getJSON() 从该文件中读取 json 数据了解更多信息:http://api.jquery.com/jQuery.getJSON/

    【讨论】:

    • 是的,你是对的。我可以使用本地 JSON 文件,它工作正常。但是现在我想改进这个过程,我的意思是我不想在本地存储 JSON 文件,JavaScript 仍然可以从 Python 中检索我的 JSON 数据。 return json.dumps(components) 之类的东西,但我不知道如何用 JavaScript 实现它。
    【解决方案3】:

    您正在渲染 HTML 并将其作为响应发送。如果您希望使用 JSON,则必须更改。您应该在 main.py 中返回 JSON,而您将从 Javascript 发送 HTML(GET 或 POST)并将其返回。

    def componentSelectBar(self, brand, category):
        /* Your code goes here */
        j = json.dumps(components)
        // Code to add a persistent store here
        rowarraysFile = 'public/json/component.json'
        f = open(rowarraysFile, 'w')
        print >> f, j
        // Better to use append mode and append the contents to the file in python
        return j //Instead of string ok
    
    
    @cherrypy.expose
    def codeSearch(self):
        json_request = cherrypy.request.body.read()
        import json # This should go to the top of the file
        input_dict = json.loads(json_request)
        modelNumber = input_dict.get("modelNumber", "")
        category = input_dict.get("category", "")
        brand = input_dict.get("brand", "")
        /* Your code goes here */
        json_response = self.search.componentSelectBar(cherrypy.session['brand'], cherrypy.session['category'])
        return json_response
    

    这里,我只为成功的场景添加。但是,您应该在 componentSelectBar 函数中管理失败场景(可以提供尽可能详细信息的 JSON 错误响应)。这将帮助您使codeSearch 函数尽可能简单,并从长远来看有帮助(阅读维护代码)。

    我建议您阅读 PEP 8 并将其应用于代码,因为它是所有 Python 程序员的一种规范,并帮助任何接触您的代码的人。

    编辑:这是一个示例 javascript 函数,它将发出一个发布请求并获取 JSON 响应:

    searchResponse: function(){
      $.ajax({
        url: 'http://localhost:8080/codeSearch', // Add your URL here
        data: {"brand" : "Levis", "category" : "pants"}
        async: False, 
        success: function(search_response) {
          response_json = JSON.parse(search_response)
          alert(response_json)
          // Do what you have to do here;
          // In this specific case, you have to generate table or any structure based on the response received
        }
      })
    }
    

    【讨论】:

    • 抱歉,在 main.py 中返回 JSON 数据后,我仍然不知道如何在 JavaScript 中使用此 JSON 数据。你介意告诉我如何在 JavaScript 中使用返回的 JSON 数据来创建动态下拉列表吗?
    • 当然。我将使用一个获取 JSON 数据的示例 JS 函数来更新答案:)
    • 添加了一个示例 JS 函数。通过这种方式,您将收到 JSON 响应。但是,您必须使用 JavaScript 渲染它才能以所需的格式显示输出。
    • 如果我在main.py 中返回json_response,我将无法加载我的网页,对吗?反而会出现 JSON 数据,这不是我想要的。
    猜你喜欢
    • 2012-08-11
    • 2018-01-15
    • 2018-04-04
    • 1970-01-01
    • 2017-06-10
    • 1970-01-01
    • 2023-03-12
    • 2014-06-26
    • 2021-05-24
    相关资源
    最近更新 更多