【问题标题】:Variable passed to from javascript to Python via AJAX - is not found通过 AJAX 从 javascript 传递到 Python 的变量 - 未找到
【发布时间】:2019-11-19 11:26:11
【问题描述】:

我想要做的是通过 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']

有什么建议吗?

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

【问题讨论】:

    标签: javascript python jquery ajax flask


    【解决方案1】:

    不要使用 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);
            }
        });
    

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

    【讨论】:

    • 按建议更改,但随后会产生以下错误:加载资源失败:服务器响应状态为 400(错误请求)我在烧瓶视图函数中使用 request.get_json()
    【解决方案2】:

    代替

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

    试试

    data: ids 在 AJAX 调用中和

    data['id'] = request.POST.get('user_id') 在 Python 中。

    【讨论】:

      【解决方案3】:

      您可以使用获取有关 POST 信息的方式

      request.get_json() # and you access the variable that you wanna
      
      # This is another way
      request.data # Will returns a dict
      
      # When do you needs access a get parameters
      request.args.get('param')
      

      【讨论】:

      • 在我的 python 代码中尝试你的建议: data = request.get_json(force=True) print(data) 但是,这会产生以下错误:加载资源失败:服务器响应状态为 400(错误请求)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-29
      • 2011-11-08
      • 2017-01-17
      • 1970-01-01
      相关资源
      最近更新 更多