我正在探索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>'
请在下面的代码中找到predict.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);
}
});
});
});
最后,使用上面的HTML呈现的app.py代码,并在接收到在表单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有什么问题吗? 请帮忙。
最佳 AR
答案 0 :(得分:0)
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