索引.html
<div class="div-inputs">
<input type="text" id="input" placeholder="Enter expression" value="1 2"/>
<input type="submit" id="btn" value="Execute"/>
</div>
<input type="text" id="output" readonly="readonly">
<script src="{{url_for('static', filename='js/jquery-3.2.1.min.js')}}"></script>
<script type="text/javascript">
document.querySelector('#btn').addEventListener('click', (e) => {
let equation = document.querySelector('#input').value;
$.ajax({
url: "/",
type: "POST",
data: equation,
success: function(){
console.log("successfull POST");
let result = {{evaluate}}
document.querySelector('#output').value = result;
}
});
});
</script>
主檔案
from flask import Flask
from flask import url_for, jsonify, render_template, request, json
from math import *
app=Flask(__name__)
@app.route('/', methods=["GET","POST"])
def index() :
evaluate = ""
if request.method == 'POST':
toEvalFromJS = request.get_json()
evaluate = eval(str(toEvalFromJS))
return render_template('index.html', evaluate=evaluate)
return render_template('index.html')
if __name__ == "__main__":
app.run(port=10, debug=True)
錯誤
(index):26 successfull POST
(index):28 Uncaught ReferenceError: Cannot access 'result' before initialization
at Object.success ((index):28:53)
at i (jquery-3.2.1.min.js:2:28017)
at Object.fireWith [as resolveWith] (jquery-3.2.1.min.js:2:28783)
at A (jquery-3.2.1.min.js:4:14035)
at XMLHttpRequest.<anonymous> (jquery-3.2.1.min.js:4:16323)
I know what the error means but I could only get such far.
I have already read the following questions:
- jquery - return value using ajax result on success
- How to return the response from an asynchronous call
but they did not help me solve my problem.
What I want to do: User input an expression string, then click on the submit button and get the evaluated string back.
How could I get the evaluated string?
I am new to flask, I do it just for practice
uj5u.com熱心網友回復:
主要問題是您{{evaluate}}以錯誤的方式使用。您期望 JavaScript 會從服務器獲取資料,并將其替換{{evaluate}}為新值。但事實并非如此。
Flask{{evaluate}}用空字串替換,它發送帶有空字串的 HTML - 當您加載頁面index.html并且瀏覽器有帶有空字串的 HTML(它不知道有{{evaluate}})時,瀏覽器會發送空字串。
當$.ajax再次獲取它時,Flask 會{{evaluate}}在模板中替換index.html,它會發送帶有新值的新 HTML 來代替,{{evaluate}}但它不能替換瀏覽器中原始 HTML 中已有的空字串 - 它不能以這種方式作業。
JavaScript獲取新的 HTML,data你sucess: function(data){...}必須撰寫使用它的代碼data。但是,如果您將 ajax 發送到僅回傳結果(沒有其他 HTML)的單獨 URL,它可能會更簡單。然后就可以顯示了data
sucess: function(data){
document.querySelector('#output').value = data;
}
后來還有另一個問題。
Ajax 將其與標準標頭一起發送POST form并Flask查看它,并將資料轉換為request.form空request.get_json的(因為一切都在 中request.form)。
form但是有些字符在and中具有特殊含義url(即 使用而不是空格),它會自動取消轉義資料并放置space而不是 .
要得到 你必須得到raw data使用request.get_data()
或者您必須使用ajax標頭發送。application/jsonget_json()
$.ajax({
...
contentType: "application/json; charset=utf-8",
...
})
最少的作業代碼
我使用render_template_string而不是render_template將所有內容放在一個檔案中 - 現在每個人都可以簡單地復制并運行它。
我也https://cdnjs.cloudflare.com用來加載jquery,所以它不需要本地檔案jquery。
from flask import Flask, url_for, jsonify, render_template_string, request, json
from math import * # `import *` is not preferred
app = Flask(__name__)
@app.route('/')
def index():
return render_template_string("""
<div >
<input type="text" id="input" placeholder="Enter expression" value="1 2"/>
<input type="submit" id="btn" value="Execute"/>
</div>
<input type="text" id="output" readonly="readonly">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP u1T9qYdvdihz0PPSiiqn/ /3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script type="text/javascript">
document.querySelector('#btn').addEventListener('click', (e) => {
let equation = document.querySelector('#input').value;
$.ajax({
url: "/data",
type: "POST",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(equation),
success: function(data){
console.log("successfull POST");
console.log(data);
document.querySelector('#output').value = data;
}
});
});
</script>
""")
@app.route('/data', methods=['POST'])
def data():
print('json:', request.get_json()) # `None` if there is no `contentType: "application/json; charset=utf-8"` in `$.ajax`
print('data:', request.get_data())
print('form:', request.form)
equation = json.loads(request.get_data().decode())
print('equation:', equation)
if equation:
result = eval(equation)
else:
result = "wrong data"
return jsonify(result)
if __name__ == "__main__":
#app.debug = True
app.run(port=5010)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/443368.html
標籤:javascript python jquery ajax flask
上一篇:矩陣的最大成本
