繁体   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