簡體   English   中英

如何從燒瓶返回單個字符串值到 Html 標簽標簽?

[英]How to return single string value from flask to Html label tag?

我正在嘗試與我的機器學習模型進行交互,我可以在其中從 HTML 獲取燒瓶路由方法的輸入值,但無法將帶有字符串值的響應傳遞給 ajax 查詢。

按鈕的點擊擊中了ajax函數並確實轉到了flask路由函數,但它甚至沒有擊中ajax函數的成功或錯誤部分。 給出 405 Method not Allowed 錯誤。 127.0.0.1 - - [12/Oct/2020 13:15:17] “POST / HTTP/1.1” 405 -

我是 Flask 的新手,不知道數據綁定選項。 任何幫助,將不勝感激。

HTML 部分

<html>
    <head>
    <meta charset="utf-8">
    <link rel="stylesheet" href="{{ url_for('static', 
     filename='css/bootstrap.min.css') }}">
           <title>Twitter Sarcasm Detection</title>
    <script 
   src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"> 
    </script> 
    <script src="static/js/signUp.js"></script>
    <style>
    h1 {
        margin-top: 13rem;
        color: chocolate
    }
    p{
        margin-top: 36px;
    }
    .form-group{
        margin: 3rem !important;
    }
    </style>

    </head>
    <body>
<div class="container" style="text-align:center">
<h1>Twitter Sarcasm Detection</h1>
<p>Enter the text below to find out if its Sarcastic or not!</p>
<form action="http://localhost:5000/" method="post">
    <div class="form-group">
    <input type="text" class="form-control" id="userText" name="userText">
    </div>
    <button id="submit" class="btn btn-primary">Submit</button>
    <input type="reset" value="Reset" class="btn btn-primary">
    <div class="form-group">
    <label id="prediction" name="prediction"></label>
    </div>
</form>
</div>

腳本文件中的 AJAX 查詢

    $(function(){
    $('#submit').click(function(){
        $.ajax({
            url: '/predictSarcasm',
            data: $('form').serialize(),
            type: 'POST',
            success: function(response){
                    $('#prediction').val(response.result);
                },
                error: function(error){
                    console.log(error);
                }
        });
    });
});

燒瓶代碼

    from flask import Flask, render_template, json
from joblib import load

pipeline = load("text_classification.joblib")

def requestResults(text):
    tweet = pipeline.predict([text])
    if tweet == 0:
        return "Not-Sarcastic"
    else:
        return "Sarcastic"

app = Flask(__name__)

@app.route("/")
def home():
    return render_template('Index.html')
    
@app.route('/predictSarcasm', methods=['POST'])
def predictSarcasm():
    text = request.form['userText']
    prediction = requestResults(text)
    return json.dumps({'status':'OK','result':str(prediction)});

if __name__ == "__main__":
    app.run(debug=False)

你不需要為 ajax 使用表單

html代碼

<h1>Twitter Sarcasm Detection</h1>
<p>Enter the text below to find out if its Sarcastic or not!</p>
    <div class="form-group">
    <input type="text" class="form-control" id="userText" name="userText">
    </div>
    <button id="submit" class="btn btn-primary">Submit</button>
    <input type="reset" value="Reset" class="btn btn-primary">
    <div class="form-group">
    <label id="prediction" name="prediction"></label>
    </div>
</div>

阿賈克斯代碼

$('#submit').click(function(){
        $.ajax({
            url: '/predictSarcasm',
            contentType: "application/json",
           data: JSON.stringify({ "text": $('#userText').val()})
            type: 'POST',
            success: function(response){
                    $('#prediction').val(response.result);
                },
                error: function(error){
                    console.log(error);
                }
        });
    });

Python代碼

from flask import jsonify

@app.route('/predictSarcasm', methods=['POST'])
def predictSarcasm():
    json= request.get_json()
    text=json["text"]
    prediction = requestResults(text)
    return jsonify({"status":"OK",'result':str(prediction)})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM