2017-08-29 207 views
0

我有幾個由JQuery前端生成的數組。使用AJAX將JSON數據傳遞給Flask服務器?

EDIT1(基於由埃德加·恩裏克斯答案)

my_jq.js:

var a = ['one','two']; 
var b = ['three','four']; 
var c = ['five']; 
var d = ['six','seven','eight']; 
var e = ['nine','ten','eleven']; 
var newArray = []; 

//jsonify to send to the server 
$.ajax('/output', { 
    type: "POST", 
    contentType: "application/json", 
    dataType: "json", 
    data: JSON.stringify(postData), 
    success: function(data, status){ 
     console.log(newArray); 
     console.log(status);} 
}); 

我傳遞選定的值到服務器(瓶/蟒蛇),並將它計算笛卡爾產品。然後我需要顯示在屏幕output.html

@app.route('/output', methods = ['GET','POST']) 
def output(): 
    data1 = request.get_json(force = True) 
    a = data1['a'] 
    b = data1['b'] 
    c = data1['c'] 
    d = data1['d'] 
    e = data1['e'] 
    newArray = [a,b,c,d,e] 
for element in itertools.product(*newArray): 
    print(element) 
    return jsonify(element) 
return render_template('output.html', element = element) 

output.html輸出:

<p>{{ element }}</p> 

EDIT2:

有了這個代碼,該/output.html產生:

"Bad Request 
Failed to decode JSON object: Expecting value: line 1 column 1 (char 0)" 

檢查顯示:

"Failed to load resource: the server responded with a status of 500 (INTERNAL SERVER ERROR)" 

爲什麼不認識它?

回答

2

對於你的jquery代碼你可以有一個JavaScript對象(將對象的屬性命名爲數組變量僅用於約定)。事情是這樣的:

var a = ['one','two']; 
var b = ['three','four']; 
var c = ['five']; 
var d = ['six','seven','eight']; 
var e = ['nine','ten','eleven']; 

var postData = { 
    a: a, 
    b: b, 
    c: c, 
    d: d, 
    e: e 
} 

$.ajax({ 
    url: "/output", 
    type: "POST", 
    contentType: "application/json", 
    data: JSON.stringify(postData), 
    success: function(data){/* do something */} 
}); 

回到你的服務器,你可以這樣做:

@app.route('/output', methods=['POST']) 
def output(): 
    result = [] 
    data = request.get_json() 
    a = data['a'] #will give you array a 
    b = data['b'] #will give you array b 
    c = data['c'] #will give you array c 
    d = data['d'] #will give you array d 
    e = data['e'] #will give you array e 
    newArray = [a, b, c, d, e] 
    #To test you got the data do a print statement 

    print(newArray) 

    # The for loop is not necessary if you pass the newArray directly to 
    # your template "output.html". 
    # 
    #for element in newArray: 
    # result.append(element) 
    # 
    #like this 
    return render_template('output.html', element=newArray) 

您可以在output.html顯示結果但是你決定最適合你,只記得

希望它有助於!

+0

謝謝! ajax中'成功'的目的是什麼? –

+0

@FeyziBagirov如果請求成功,將被調用的函數。 [閱讀更多關於$ .ajax()](http://api.jquery.com/jquery.ajax/) –

+0

當我運行它時,我得到「NameError:name'newArray'未定義」。它似乎並不認可newArray作爲一個變量。可能是什麼原因? –

相關問題