我是 javascript 新手,我創建了一個 Flask 站點,我想關注 ansible 塔式作業。我創建了一個特定的路線:
@app.route("/tower/<int:id>", methods=['POST','GET'])
def status(id):
launch = True
job_info = {}
status = refreshstatus(id)
return render_template(
'tower.html',
job_info = job_info,
status = status,
launch = launch,
id = id)
@app.route("/tower", methods=['POST','GET'])
def tower():
launch = False
if request.method == 'POST':
keyword = request.form['launchjob']
logger.info("Test | Keyword var => " keyword)
template_id = request.form['template_id']
job_info = launch_job(template_id, keyword)
launch = True
return render_template('tower.html', job_info = job_info, launch = launch)
else:
return render_template('tower.html')
我的js腳本:
function refresh() {
$.ajax({
url: '/tower/' id,
dataType: 'json',
id: { id : job_info.job_id },
success: function(data) {
$('#statustable').html(data);
}
});
setTimeout(refresh, 10000);
console.log('refresh')
};
$(function(){
refresh();
});
和我的 html 檔案
<th scope="row"></th>
<td> {{ job_info.job_id }}</td>
<td><p class="text-warning" id="statustable">{{ job_info.job_status }}</p></td>
<td><a href="{{ job_info.url }}" target="_blank">Lien vers le stdout</a></td>
當我手動重繪 時,它的作業狀態會發生變化,但不會自動重繪 。你能幫忙嗎 ?
謝謝
大衛
uj5u.com熱心網友回復:
JavaScript 看不到您服務器的變數。job_info.job_id不會在您的瀏覽器中定義。
如果你想在那里使用它,你需要以某種方式將變數值傳輸到瀏覽器。
- 一種方法是從
<td>{{ job_info.job_id }}</td>. - 更好的方法是使用HTML 資料屬性。
如果您在服務器端像這樣更改視圖:
<tr data-job-id="{{job_info.job_id|tojson|forceescape}}">
<th scope="row"></th>
<td>{{ job_info.job_id }}</td>
<td><p class="text-warning" id="statustable">{{ job_info.job_status }}</p></td>
<td><a href="{{ job_info.url }}" target="_blank">Lien vers le stdout</a></td>
</tr>
然后您可以data-job-id="..."在客戶端使用 jQuery訪問該值:
function refresh() {
const id = $('#statustable').closest("tr").data('job-id');
$('#statustable').load('/tower/' id);
setTimeout(refresh, 10000);
};
$(refresh);
- 與Jinja 的
tojsonfilter一起,資料屬性允許您將復雜資料(如完整job_info結構)傳輸到客戶端,而不僅僅是像單個 ID 這樣的簡單值。警告:請記住使用forceescape過濾器以避免出現問題。 - 移至
data-job-id="..."HTML 中最有意義的元素。 $(element).load(url)是$.ajax(url)->success->的簡寫形式$(element).html(response)。請參閱https://api.jquery.com/load/。$(refresh)是 的縮寫形式$(function () { refresh(); })。請參閱https://api.jquery.com/jquery/#jQuery3。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/391084.html
標籤:javascript 阿贾克斯 烧瓶
