[英]How to pass data from Flask to Javascript?
我一直在嘗試制作一個基本的燒瓶應用程序。 我在app.py
文件中以jasonify
格式返回了經過字符串processed text
。 但是我不知道如何將特定的字符串值接收到index.html
文件中的java-script
變量中。
誰能幫我這個忙嗎? 以下代碼是文件app.py
的一部分:
@app.route('/', methods = ['POST'])
def my_form_post():
MAX_SEQUENCE_LENGTH = 30
best_model = load_model('BalanceNet.h5')
#data2 = pd.read_csv('train.csv')
text = request.form['u']
x = text.split(' ')
y = [int(k) for k in x]
data_int_t = pad_sequences([y, [], [], [], []], padding='pre', maxlen=(MAX_SEQUENCE_LENGTH-5))
data_test = pad_sequences(data_int_t, padding='post', maxlen=(MAX_SEQUENCE_LENGTH))
y_prob = best_model.predict(data_test)
processed_text = str(y_prob[0][0])
return jsonify({'request' : processed_text})
這是為您提供的概念證明應用程序:
./app.py
from flask import Flask, jsonify, request, render_template
app = Flask(__name__)
@app.route('/')
def home():
return render_template('index.html')
@app.route('/calc', methods=['POST'])
def calc_estimation():
text = request.form['text']
results = process_text(text)
return jsonify(results)
def process_text(text: str) -> str:
return [text.upper()] * 10
if __name__ == '__main__':
app.run()
./templates/index.html
<form method="POST" action="/calc" data-calc-form>
<input type="text" name='text'>
<button>Calculate</button>
<pre data-preview></pre>
</form>
<script>
window.addEventListener('DOMContentLoaded', init);
function init() {
const form = document.querySelector('[data-calc-form]');
const textInput = document.querySelector('[name=text]');
const preview = document.querySelector('[data-preview]');
form.addEventListener('submit', async (e) => {
e.preventDefault();
const text = textInput.value;
const results = await fetchEstimations(text);
preview.textContent = JSON.stringify(results, null, 4);
});
}
async function fetchEstimations(text) {
const payload = new FormData();
payload.append('text', text);
const res = await fetch('/calc', {
method: 'post',
body: payload
});
const estimation = await res.json();
return estimation;
}
</script>
您如何使用JSON響應由您決定,這里我只是按原樣顯示它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.