使用AJAX将JSON数据传递给Flask服务器?

使用AJAX将JSON数据传递给Flask服务器?

问题描述:

我有几个由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)" 

为什么不认识它?

对于你的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作为一个变量。可能是什么原因? –