Alf*_*wan 4 javascript python ajax jquery flask
我有一个问题,我无法在使用 ajax 发布数据后打开 render_template。这是我的 ajax 代码。
if ($(this).attr("value") == "button-three") {
var skoring = getRadioVal(document.getElementById('mentodeNegasi'),'negasi')
$.ajax({
data: { metodeSkoring: skoring },
type: 'POST',
url: '/evaluasiModel'
})
}
Run Code Online (Sandbox Code Playgroud)
这是我的服务器代码。
@app.route('/evaluasiModel', methods=['POST',"GET"])
def evaluasiModel():
metodeSkoring = request.form['metodeSkoring']
metodeSkoring = int(metodeSkoring)
return render_template("evaluasiModelKlasifikasi.html", hasilSkoring = metodeSkoring)
Run Code Online (Sandbox Code Playgroud)
我希望在将数据ajax发布到“def evaluasiModel()”后,我可以打开render_template“evaluasiModelKlasifikasi.html”并获取数据metodeSkoring以显示在此模板中。
你为什么需要那个帖子功能?您可以在使用重定向从用户那里获取值后简单地加载页面。
以下是如何执行此操作的示例。我模拟了一个类似的场景。为此我需要
application.py : 作为路由控制器index.html : 作为主模板evaluasiModelKlasifikasi.html : 作为重定向模板application.py:
import json
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
@app.route('/index')
def show_index():
return render_template("index.html")
@app.route('/evaluasiModel/<metodeSkoring>')
def evaluasiModel(metodeSkoring):
return render_template("evaluasiModelKlasifikasi.html", hasilSkoring = metodeSkoring)
if __name__ == '__main__':
app.run(debug=True)
Run Code Online (Sandbox Code Playgroud)
index.html:
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
<script
src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
</head>
<body>
<div id="container">
<input type="text" id="mentodeNegasi" />
<button id="get_button">Get score</button>
</div>
<script type="text/javascript">
$(document).ready(function(){
$("#get_button").on("click",function(){
var skoring = $("#mentodeNegasi").val();
window.location.href = '/evaluasiModel/'+skoring;
})
})
</script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
evaluasiModelKlasifikasi.html
<!DOCTYPE html>
<html>
<head>
<title>evaluasiModel</title>
</head>
<body>
<div id="container">
<div id="result">
hasilSkoring: {{ hasilSkoring }}
</div>
</div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
输出:
索引页:
重定向后:
示范: