在网页上显示 ML 模型的结果



我正在探索RESTful Flask API,作为学习,我用HTML创建了一个小的Web表单。请参阅下面的 HTML 代码。

<!DOCTYPE html>
<html>
<h2>User Input</h2>
<body
<script>
src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> 
</script>
<script src="/static/js/predict.js"></script>
<p>Please enter the Power prices per unit</p>
<form method="get" action='/predict' target ="_blank" 
enctype="multipart/form-data">
New Value - 1:<br>
<input type="number" id="New_val_1">
<br>
New Value - 2:<br>
<input type="number" id="New_val_2">
<br><br>
<button id="btnpredict" type="button">Predict</button>
</form> 
<p>If you click the "Submit" button, the form-data will be sent to a page 
called "/action_page.php".</p>
</body>
</html>'

请参阅下面的代码以进行预测.js。这是一个 JQuery AJAX

$(function(){
$('#btnpredict').click(function(){
$.ajax({
url: '/predict',
data: JSON.stringify({userInput: uInput})
type: 'GET',
contentType: 'application/json', 
success: function(response){
("#results").text(response.results);
},
error: function(error){
console.log(error);
}
});
});
});

最后,使用 app.py 代码,其中呈现上述 HTML 并在收到传递在表单上的值时使用 ML 模型。

from flask import Flask, redirect, request, render_template,json, Response
import statsmodels.api as sm
import numpy as np
from sklearn.externals import joblib
app = Flask(__name__)
@app.route('/')
@app.route('/home')
def home():
return render_template('index.html')
@app.route('/predict', methods = ['GET'])
def predict():
if request.method=='GET':
X_value_new_1 = request.values.get('New_val_1') 
X_value_new_2 = request.values.get('New_val_2')
X_1,X_2 = X_value_new_1,X_value_new_2
testData = np.array([X_1,X_2]).astype(np.float).reshape(-1,1)
testData=sm.add_constant(testData)
pred = Regression_model.predict(testData)
dump = json.dumps({'prediction':list(pred)})
resp = Response(dump,mimetype='application/json')
return resp
return None
def load_model():
global Regression_model
Regression_model = joblib.load('E:/model_file_save')
if __name__ == "__main__":
print("**Starting Server...")
load_model()
app.run(debug=True)

现在的问题是: 当我单击"预测"按钮时,没有任何反应。但是,如果在地址栏上,如果我写了"http://localhost:5000/predict?New_val_1=1000&New_val_2=2000",那么我会得到 JSON 格式的正确预测值。

如何解决这个问题?JQuery有什么问题吗? 请帮忙。

最好 阿

Read textbox values e.g. $("#tag").val() and concate with ajax url e.g. 
predict?New_val_1=1000&New_val_2=2000'
and remove data property. You can also pass values using data property see below link for example.

https://www.codeproject.com/Questions/870797/How-to-pass-textbox-value-to-other-page-using-Jque

最新更新