如何访问flask请求中的请求数据

问题描述 投票:0回答:1

我试图通过javascript和ajax访问我用python编写的POST方法。以下是javascript代码。

       $('#aht_btn').click(function(){

 var input1 = $("#data").val();
    alert("input.."+input1);    
    $.ajax({
    url: "http://localhost:5000/train",
    type: 'POST',
    dataType: "json",
    data: input1,
    success: function (data) {
    alert(data);

    },
    error: function (error) {
    alert(error);
       // $('.messages').html(error);
    }
});

我的python POST方法如下。

@app.route('/train',methods = ['POST', 'GET'])
def train_system():
vectorizer = TfidfVectorizer(sublinear_tf=True, max_df=0.5,
                                stop_words='english')

features_train, features_test, labels_train, labels_test = 
TwitterProcess.preprocess()

#logreg=LogisticRegression()
tLogReg=time()
Twitter.logreg.fit(features_train, labels_train)
print "training time for Logistic Regression:", round(time()-tLogReg, 3), 
"s"
t2 = time()
pred = Twitter.logreg.predict(features_test)

while True:
    #flag=raw_input("Do you want to classify the data?(Y/N)")
    print "Enter classification"

    print request.json

    flag = request.get_json()

    print flag

当我打印这个“旗帜”时,它打印无。

我如何通过我的Python post方法接收通过Ajax调用发送的请求数据。

javascript python ajax post
1个回答
1
投票

尝试类似下面的内容..你必须添加'contentType:'application / json; charset = UTF-8''

$('#aht_btn').click(function(){
    var input1 = $("#data").val();
    alert("input.." + input1);   
    request_data = { input1 } 
    $.ajax({
        url: "http://localhost:5000/train",
        type: 'POST',
        dataType: "json",
        contentType: 'application/json;charset=UTF-8',//missing this
        data: JSON.stringify(request_data),
        success: function (data) {
            alert(data);

        },
        error: function (error) {
            alert(error);
       }
    });
});
© www.soinside.com 2019 - 2024. All rights reserved.