我對 Web 開發比較陌生?;旧希艺跓恐袆摻ㄒ粋€應用程序。我現在要做的是測試一個 AJAX 函數,看看它是否工作。AJAX 函數從 html 讀取無線電輸入。我想在 html 中顯示 AJAX 調用,以查看我的代碼是否正常工作。這是我的 html 代碼(index.html):<div class="form-check form-check-inline"> <input class="form-check-input" type="radio" name="inlineRadioOptions1" id="option1" value="option1"> <label class="form-check-label" >Yes</label></div><div class="form-check form-check-inline"> <input class="form-check-input" type="radio" name="inlineRadioOptions1" id="option2" value="option2"> <label class="form-check-label">No</label></div><div class="form-check form-check-inline"> <input class="form-check-input" type="radio" name="inlineRadioOptions1" id="option3" value="option3"> <label class="form-check-label">Dunno</label></div>這是我的 AJAX 函數:$(function(){ $('#btnSubmit').click(function(){ var radioValue1 = $("input[name=inlineRadioOptions1]:checked").val(); $.ajax({ url: '/process', data: {value1: radioValue1}, type: 'POST', success: function(response){ console.log(response); }, error: function(error){ console.log(error); } }); });});這是我在python中的代碼:from flask import Flask, render_template, request, jsonify# App config.DEBUG = Trueapp = Flask(__name__)app.config.from_object(__name__)app.config['SECRET_KEY'] = '7d441f277y7ttt8t88tb'@app.route("/")def index(): return render_template('index.html')@app.route('/process', methods = ['POST'])def process(): v1 = request.form['value1'] return jsonify({'v1': v1})if __name__ == "__main__": app.run(debug = True)現在我想使用 div 標簽在 index.html 中顯示值 v1。我怎樣才能做到這一點?
2 回答

藍山帝景
TA貢獻1843條經驗 獲得超7個贊
首先,您需要在響應中設置標題,text/json
以便成功函數將您response
作為 json 對象。那么你可以像這樣閱讀它:
response.v1
要更改 html 值,您可以通過 id 調用元素:
$('#id_v1').text(response.v1)
現在你需要一個容器來顯示數據,這樣你就可以在你的 html 中添加它:
<input id="id_v1"> or <div id="id_v1"></div>

慕村9548890
TA貢獻1884條經驗 獲得超4個贊
插入<div id="result"></div>您的index.html并將結果放在成功處理程序中:
$.ajax({
url: '/process',
data: {value1: radioValue1},
type: 'POST',
success: function(response){
console.log(response);
$('#result').text(response.v1);
},
error: function(error){
console.log(error);
}
});
添加回答
舉報
0/150
提交
取消