简体   繁体   中英

Flask populate python list item into drop down list selector

I am very new to Flask. I have my python function that retrieves a list of years from the database, but I can't loop through the list and populate into the dropdown selector.

I am using ajax but not sure how to make the python list a json format for javascript to populate elements in the dropdown box. What I have now is returning the whole list as one option.

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 file:

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>

I found a way of loop through the object in the .done section.

.done(function(data) {

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM