2016-09-20 78 views
1

我使用Python cherrypyJinja來爲我的網頁提供服務。我有兩個Python文件:Main.py(處理網頁)和search.py​​(服務器端函數)。
我創建一個基於本地JSON文件名爲component.json(按功能componentSelectBarsearch.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>"); 
     }); 
    }); 
+0

基本上,你需要一個處理程序與@標記cherrypy.tools.json_out裝飾返回字典/名單。只需更改JS中的URL,就是這樣。 您的問題目前包含太多的信息,這與問題無關。請考慮減小它的大小,並提供最少量的代碼,以免使讀者感到困惑。 – webKnjaZ

回答

-1

要使用JSON數據直接轉換爲JavaScript,你可以使用

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

OR

您已經創建JSON文件。如果該文件是在正確的格式,那麼你可以使用jQuery jQuery.getJSON()更多的是文件中讀取JSON數據:http://api.jquery.com/jQuery.getJSON/

+0

是的,你是對的。我可以使用本地的JSON文件,並且它工作正常。但現在我想改進這個過程,我的意思是我不想在本地存儲JSON文件,JavaScript仍然可以從Python中檢索我的JSON數據。就像'return json.dumps(components)',但我不知道如何用JavaScript實現它。 –

0
  1. 存儲結果,從componentSelectBar到數據庫
  2. 暴露新的API從數據庫中結果並返回JSON到瀏覽器

演示在這裏:

在CherryPy的
@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 

文件,希望幫助: Encoding response

在你broswer,你需要得到/ 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>"); 
    }); 
}); 
-1

您正在渲染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函數,這將使POST請求,並得到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 
    } 
    }) 
} 
+0

對不起,我仍然不知道如何在_main.py_中返回JSON數據後在JavaScript中使用這個JSON數據。你介意告訴我如何使用JavaScript中的返回JSON數據來創建動態下拉列表? –

+0

當然。我將用一個JS樣本函數更新答案,它將得到JSON數據:) – thiruvenkadam

+0

增加了一個JS函數樣例。通過這種方式,您將收到JSON響應。但是,您必須使用JavaScript來呈現它,才能以所需的格式顯示輸出。 – thiruvenkadam