【问题标题】:Flask populate python list item into drop down list selectorFlask 将 python 列表项填充到下拉列表选择器中
【发布时间】:2020-06-28 18:55:17
【问题描述】:

我对 Flask 很陌生。 我的 python 函数可以从数据库中检索年份列表,但我无法遍历列表并填充到下拉选择器中。

我正在使用 ajax,但不确定如何将 python 列表设置为 json 格式,以便 javascript 填充下拉框中的元素。我现在所拥有的是将整个列表作为一个选项返回。

What I have now

app.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>`);
  });
}

index.html:

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

【问题讨论】:

    标签: javascript python json ajax flask


    【解决方案1】:

    我在 .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>`);
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-28
      • 1970-01-01
      • 2017-04-06
      • 2012-09-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多