首页 > 解决方案 > 通过 AJAX 从 javascript 传递到 Python 的变量 - 未找到

问题描述

我想要做的是通过 ajax 将值从我的 js 传递给 python(以便稍后我可以使用它来对我的数据库应用一些过滤)。

但是,每次我试图在 python 中获取它时,我都会收到以下错误:

TypeError:“NoneType”对象不可下标。

这是我的js代码:

    $(document).ready(function(){

// code to read selected table row cell data (values).
$("#myTable").on('click','button.btn.btn-primary',function(){
     // get the current row

     var currentRow=$(this).closest("tr");
     var col1 = currentRow.find("td:eq(0)").text(); // get current row 1st TD value

     var ids = {
        'user_id': col1
    };

    $.ajax({
        url: '/',
        contentType: 'application/json',
        dataType: 'json',
        data: JSON.stringify(ids),
        type: 'POST',

        success: function(response) {
            console.log(response);
        },
        error: function(error) {
            console.log(error);
        }
    });

     alert(col1);
});

});

这是我的蟒蛇:

    @app.route('/', methods=['GET', 'POST'])
    @login_required
    def index():
        if request.method == "POST":
            data = {}

            data['id'] = request.json['user_id']
            return jsonify(data)


       return render_template('index.html', title='Homepage')

发布请求似乎工作正常。仅当我尝试获取 python 时才给出错误:

    data['id'] = request.json['user_id']

关于如何去做的任何建议?

PS我不太擅长js。刚开始。将不胜感激任何帮助和指导。

标签: javascriptpythonjqueryajaxflask

解决方案


不要使用 JSON.stringify 将数据传递到 POST 请求中。在 AJAX 的 POST 请求中,您必须传递整个对象。在 python 的服务器端,您可以在代码中通过在对象键中使用的键检索数据user_id

$.ajax({
        url: '/',
        contentType: 'application/json',
        dataType: 'json',
        data: ids,
        type: 'POST',

        success: function(response) {
            console.log(response);
        },
        error: function(error) {
            console.log(error);
        }
    });

我希望这会奏效,祝你好运!!


推荐阅读