如何将数据从Javascript输入发送到Flask

时间:2019-03-20 10:29:27

标签: javascript jquery ajax flask

我有一张桌子,每一行都有按钮。如果单击按钮,例如第3行,则第3行的ID将同时显示在警报和console.log中。我最终希望将行ID发送到flask python,然后可以使用该ID号删除或复制相关行。

我需要使用Ajax发布,并且在下面的链接中使用此示例可以正常工作。 https://github.com/bsaldivaremc2/send_receive_data_with_flask

当我修改现有代码以合并上面链接中示例中的ajax帖子时,我在命令终端和控制台检查中不断收到此错误。

命令终端:

TypeError:“ int”对象不可调用 视图函数未返回有效响应。返回类型必须是字符串,元组,Response实例或可调用的WSGI,但它是整数。

控制台检查: POST http://127.0.0.1:5000/delete_data 500(内部服务器错误)

这是我的HTML / JS

test2.html

<!DOCTYPE html>
<html>

<head>

<meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <title></title>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <meta name="robots" content="noindex, nofollow">
  <meta name="googlebot" content="noindex, nofollow">
  <meta name="viewport" content="width=device-width, initial-scale=1">

<meta name="viewport" content="width=device-width, initial-scale=1">

<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<script   src="http://code.jquery.com/jquery-3.3.1.min.js"   integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="   crossorigin="anonymous"></script>
<script   src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"   integrity="sha256-VazP97ZCwtekAsvgPBSUwPFKdrwD3unUfSGVYrahUqU="   crossorigin="anonymous"></script>


<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>

<script>
    type="text/javascript"
    src="//code.jquery.com/jquery-1.9.1.js"
</script>

<title>Test 1</title>

<style>


table, th, td {
  border: 1px solid black;
  border-collapse: collapse;
}



</style>

</head>
<body>




<table id="table-test">
<tr><th>ID</th><th>Student</th><th>Delete</th></tr>

<tr><td class="ids">1</td><td>Chelsey</td><td><button id="Approved">Del</button></td></tr>

<tr><td class="ids">2</td><td>Michael</td><td><button id="Approved">Del</button></td></tr>
<tr><td class="ids">3</td><td>Jared</td><td><button id="Approved">Del</button></td></tr>
</table>



<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script   src="http://code.jquery.com/jquery-3.3.1.min.js"   integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="   crossorigin="anonymous"></script>
<script   src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"   integrity="sha256-VazP97ZCwtekAsvgPBSUwPFKdrwD3unUfSGVYrahUqU="   crossorigin="anonymous"></script>



<script type="text/javascript">




$(document).ready(function(){
$(document).on("click","#Approved",function(){
    var info = $(this).parent().siblings('.ids').text();
    var all_info  = $(this).parent().siblings("#table-test");

    alert(info);

    console.log("Del button clicked!");


    var num = info.trim().toString();

    console.log(num);
    console.log(typeof(num));

    var row = {"id": num};

    row["id"] = num;

    console.log(typeof(num));

    var server = "http://127.0.0.1:5000";
    var appdir = "/delete_data";

    $.ajax({

        type:"POST",
        url: server+ appdir,
        data: JSON.stringify(info),
        dataType: "json",
        contentType: "application/json;charset=UTF-8",
        success: function(res){

            console.log(res);
        }
    })


});

});


</script>

</body>
</html>

我的烧瓶我正在尝试将行ID号发送到delete_data视图函数。

from flask import render_template, jsonify, Flask
import json

app = Flask(__name__)

@app.route("/delete_data", methods = ["GET", "POST"])
def delete_data():


    print("Deleting selected row!")
    rf = request.form
    print(rf)


    for key in rf.keys():


        data = key


    print("DATA: ", data)

    data_dic = json.loads(data)

    id_data = data_dic["id"]

    print(data_dic)
    print(id_data)


    print(type(data_dic))
    print(type(id_data))


    return id_data





@app.route("/test2", methods = ["GET", "POST"])
def test2():


    return render_template("test2.html")


if __name__ == "__main__":

    app.run(debug=True)

任何帮助将不胜感激。谢谢!

1 个答案:

答案 0 :(得分:2)

错误消息几乎说明了一切。问题很可能是这样的:

id_data = data_dic["id"]
...
return id_data

您将返回id_data,它是int,但是您需要返回错误消息中指定的两种类型。像这样尝试:

return jsonify({'id': id_data})

编辑:要回答评论中的后续问题。在打印request.form(作为rf变量时,您会得到一个空的字典,因为您实际上没有将表单数据发布到视图函数中,而是在POST请求中发送JSON正文。要获取数据,您必须使用request.get_json()而不是request.form