簡體   English   中英

Flask 將 python 列表項填充到下拉列表選擇器中

[英]Flask populate python list item into drop down list selector

我對 Flask 很陌生。 我有從數據庫中檢索年份列表的 python 函數,但我無法遍歷列表並填充到下拉選擇器中。

我正在使用 ajax,但不確定如何使 python 列表成為 javascript 的 json 格式以填充下拉框中的元素。 我現在擁有的是將整個列表作為一個選項返回。

我現在擁有的

應用程序.py:

@app.route('/getyear', methods = ['POST'])
def getyear():
    plant = request.form['plant']
    if plant:
        year_list = mymodule.get_years.tolist()
        return jsonify({'yearList': year_list })

js文件:

function showBudgetYear() {
  $.ajax({
    data: {
      plant: $("#plant-selector").val()
    },
    type: "POST",
    url: "/getyear",
    beforeSend: function() {
      $("#loading").show();
    },
    complete: function() {
      $("#loading").hide();
    }
  }).done(function(data) {
    $("#budget-dropdown").append(`<option value="${data.yearList}">  ${data.yearList} </option>`);
  });
}

索引.html:

<select id="budget-dropdown" disabled="disabled">
                            <option value="" selected disabled>select year</option>
                            <option>year 1</option>
</select>

我在 .done 部分找到了一種循環遍歷對象的方法。

.done(function(data) {

    for(var i=0 ; i<data.yearList.length; i++){

      $("#budget-dropdown").append(`<option value="${data.yearList[i]}"> ${data.yearList[i]} </option>`);
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM