使用ajax和jQuery在Flask中根据第一个下拉菜单中选定的值填充第二个下拉菜单。

6

我在这方面没有任何进展。非常感谢提供有关此事的任何帮助!

我有两个下拉菜单,一个是经理,一个是员工。

默认情况下,经理下拉菜单包含经理列表。

我想通过查询SQL Server数据库来使用用户在经理下拉菜单中选择的经理名称,填充员工下拉菜单中的员工姓名。

例如,如果一个人在经理下拉菜单中选择汤姆作为经理,则员工下拉菜单应该以Manager = Tom的员工姓名填充。

到目前为止,我有以下代码:

路由(我用它来查询SQL Server数据库,以根据经理名称获取员工列表):

@app.route ('/getEmployees', methods=['GET'])
def getEmployees():
    engine = create_engine('mssql+pyodbc://<server name>/<DB name>?driver=SQL+Server+Native+Client+11.0')
    Base = declarative_base(engine)

    class Bookmarks(Base):
        __tablename__ = '<table name>'
        Employee = Column(String(50))
        __table_args__ = {'autoload': True}

        def __repr__(self):
            return '{} '.format(self.Employee)

    def loadSession():
        metadata = Base.metadata
        Session = sessionmaker(bind=engine)
        session = Session()
        return session
    if __name__ == "__main__":
        session = loadSession()
        return session.query(Bookmarks).filter_by(Manager='<I want to populate this with the manager name a user selects in the Manager dropdown>')

index.html 中的管理者下拉菜单

<div class="form-group">
  <select class="form-control" id="next" name="division" data-error="Required!" required>
    <option value="default" disabled selected>Select something</option>
    <option value="option1">Tom</option>
    <option value="option2">Bob</option>
  </select>  
</div>

app.py中的员工下拉菜单

Employees = QuerySelectField('Employees', query_factory=getEmployees, allow_blank=True)

在index.html中
<div class="form-group" id="sel_user">
    {{ render_field(form.Employees,class="form-control", required="required") }}
</div>

我正在使用jQuery和ajax来获取用户在经理下拉框中选择的经理名称,然后对其进行一些操作。

$(document).ready(function(){

    $("#next").change(function() {

        var Manager=($('#next option:selected').text());
        console.log(Manager);

        $.ajax({
            url: "/getEmployees",
            type: 'GET',
            contentType: 'application/json',
            dataType: 'json',
            // not sure what to do next..?
        });
    });
});

当用户从经理下拉菜单中选择一个值后,接下来我应该做什么?


请粘贴/getEmployees调用的响应。我的意思是,当您进行该调用时,您收到的代码示例。另一方面,似乎您没有为员工设置下拉菜单,它显示为type="text"(看起来像普通文本输入)。 - A. Iglesias
@A.Iglesias 非常感谢! 抱歉,我没有为/getEmployees路由定义任何模板。我的意思是,我不确定我们是否需要一个模板。 现在,当我在函数getEmployees()的下面步骤中硬编码经理的姓名(Tom或Bob)时,我能够看到填充了员工列表的员工下拉菜单。 return session.query(Bookmarks).filter_by(Manager='Tom')我只是不明白如何传递用户从经理下拉菜单中选择的经理名称,并将该值传递给上述步骤,以便我们可以查看该经理的员工姓名。 - LinuxUser
基本上,我不想硬编码经理的名字。我希望它根据经理下拉列表中选择的值动态更新。 返回session.query(Bookmarks).filter_by(Manager='<动态更新>')。 再次感谢! - LinuxUser
我已经创建了一个详细的答案,试图向您解释主要思想。看看它,让我知道进展如何。 - A. Iglesias
2个回答

3

我认为你已经接近成功了。虽然我不会Python或者Flask,但我可以给你提供主要思路。

  1. When you select the manager, you get the manager name and you have to send that name in the ajax call, so you can get it in your Route code and use it to filter the array. You can send that value using the data parameter of the ajax call...

    $(document).ready(function(){
    
        $("select#next").change(function() {
    
            var managerName = $(this).find('option:selected').text();
    
            $.ajax({
                type: 'GET',
                url: "/getEmployees",
                data: { manager: managerName }
                contentType: 'application/json',
                dataType: 'json'
            });
        });
    });
    
  2. In your ajax call, create a success callback function that will be called when you receive a successful response. Something like this...

    $(document).ready(function(){
    
        $("select#next").change(function() {
    
            var managerName = $(this).find('option:selected').text();
    
            $.ajax({
                type: 'GET',
                url: "/getEmployees",,
                data: { manager: managerName }
                contentType: 'application/json',
                dataType: 'json',
                success: function(response) {
                }
            });
        });
    });
    
  3. You could also add a check to verify if you've selected manager or unselected. In case you unselect manager, you have can empty the employee select, disable it, show all employees, or whatever you want.

    $(document).ready(function(){
    
        $("select#next").change(function() {
    
            if ($(this).val() != 'default') {
    
                var managerName = $(this).find('option:selected').text();
    
                $.ajax({
                    type: 'GET',
                    url: "/getEmployees",,
                    data: { manager: managerName }
                    contentType: 'application/json',
                    dataType: 'json',
                    success: function(response) {
                    }
                });
            }
            else {  // No manager selected.
                // Do what you wnat when there's no manager selected.
                // For example, if you'd want to empty and disable the employees select...
                $('select#sel_user').html('').prop('disabled',true);
            }
        });
    });
    

现在我遇到了帮助你的问题,因为我对Python/Flask的知识不足:

  • In your Route code, you have to read the manager parameter sended with the GET ajax call. I don't know how you do that in python/flask but it has to be easy. In php would be just $_GET['manager']. With a quick search, it looks like it could be something like request.GET['username'], but you'll know it way better than me. You have to get that parameter and put that value in the last return line, something like...

    return session.query(Bookmarks).filter_by(Manager=request.GET['username'])
    
  • Is not clear to me the format of this response, so I don't know how to extract the info to create the employees select. Looking at your ajax call, you say the response is in JSON format, but I would need to see an example of that response to shw you the exact code. The idea is that you have to get that info and create the options in the success function of the ajax call, and then put that options in the employees select. Something like...

    // Imagine that your response is an array of objects similar to this
    // [{"name": "Tommy", "other": "value10"},{"name": "Jim", "other": "value32"},...]
    
    success: function(response) {
    
        var options = [];
        for (var i=0, l=response.length; i<l; i++)
            options.push('<options value="'+response[i].other+'">'+response[i].name+'<options>');
    
        $('select#sel_user').html(options.join(''));
    }
    

我认为通过这些,你可以对如何进行有个大致的了解,并根据自己的实际需求进行适应。希望对你有所帮助。


2
使用AJAX/Jquery
您可以像这样做:
您有两个下拉选择框,一个是经理选择,第二个是员工选择,员工选择下拉菜单的值取决于经理选择。
第一个选择下拉菜单:
<select id="manager_select">
</select>

<select id="employee_select">
</select>

/* 这将填充您的管理选择器 */
$.ajax({
    url: 'url that will display all list'
    dataType: 'json',
    type: 'get',
    success: function(data){
      var output = "";
       $.each(data, function(a,b){
          output += "<option value='"+b.id+"'>"+b.manager_select_name+"  </option>"
        $("#manager_select").append(output);
       });
    }
})

/* 当你改变经理的值时,这将填充您的员工选择*/

$(document).on("change", "#manager_select", function(){ var manager_id = $(this).attr("id");

 $.ajax({
     url: 'url that will display employee data where manager_id = manager_id ',
     type: 'POST',
     dataType: 'json',
     data: { 'manager_id' : manager_id } /* you are passing manager_id*/
     success: function(data){
          $("#employee_select").empty();
          var output = "";
          $.each(data, function(a,b){
              output += "<option id="+b.employee_id+">"+b.employee_desc+"</option>";
          })
          $("#employee_select").append(output);
     }
 })

})


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接