使用ajax调用python mongoDB函数

时间:2018-12-07 23:46:58

标签: javascript python ajax mongodb flask

我想知道是否可以使用AJAX进行mongoDb查询?我的流程将是这样,用户单击一个按钮将触发我的python代码中的数据库查询,该查询的结果将显示在页面上。我是AJAX的新手,似乎无法使用它。

我找到了一些对我有用的AJAX示例,直到我解开它们的pymongo游标并尝试通过AJAX发送该数据为止。

如果不支持此功能,那么如何使用flask进行异步数据库查询?

这是我的python代码

@app.route('/')
def index():
    return render_template('form.html')

@app.route('/ajaxPythonCall', methods=['POST'])
def ajaxPythonCall():

    email = request.form['email']
    name = request.form['name']

    users = mongo.db['auto_perf'].find().distinct("users")


    return jsonify({'name' : users})

这是我的AJAX代码

$(document).ready(function() {

    $('form').on('submit', function(event) {

        $.ajax({
            data : {
                name : $('#nameInput').val(),
                email : $('#emailInput').val()
            },
            type : 'POST',
            url : '/ajaxPythonCall'
        })
        .done(function(data) {

            if (data.error) {
                $('#errorAlert').text(data.error).show();
                $('#successAlert').hide();
            }
            else {
                $('#successAlert').text(data.name).show();
                $('#errorAlert').hide();
            }

        });

        event.preventDefault();

    });

}); 

0 个答案:

没有答案