使用ajax和jQuery根据烧瓶中第一个下拉列表中选择的值填充第二个下拉列表 [英] Populate second dropdown based on the value selected in the first dropdown in flask using ajax and jQuery

查看:85
本文介绍了使用ajax和jQuery根据烧瓶中第一个下拉列表中选择的值填充第二个下拉列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对此一无所知.任何与此有关的帮助将不胜感激!

I am not getting anywhere on this. Any help regarding this would be greatly appreciated!

我为经理和员工提供了两个下拉菜单.

I have two dropdowns for Managers and Employees.

管理员"下拉列表默认包含管理员"列表.

Managers dropdown contains a list of Managers by default.

我想通过使用用户在Managers下拉列表中选择的Manager名称查询SQL Server数据库,用雇员姓名填充Employees下拉列表.

I want to populate Employees dropdown with the employees name by querying a SQL Server database with the Manager name a user selects in Managers dropdown.

例如如果某人在经理"下拉列表中选择汤姆"作为经理,则员工"下拉列表应使用经理=汤姆"的员工名称填充.

So for e.g. if a person selects Tom as the Manager in the Managers dropdown then the Employees dropdown should populate with the Employees name where Manager = Tom.

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

So far I have the following code:

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

Route (which I am using to query SQL Server database to get employees list based on a manager name):

@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中的经理"下拉列表

Managers dropdown in 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 dropdown in app.py

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

在index.html

In index.html

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

我正在使用带有ajax的jQuery来获取用户在管理器下拉列表中选择的管理器名称,然后对其进行操作.

I am using jQuery with ajax to get the Manager name a user selects in the manager dropdown and then do something with it..

$(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..?
        });
    });
});

一旦我在管理员"下拉列表中选择了用户所需要的值,有人可以帮我下一步应该做什么吗?

Can anyone please help as what I should do next once I have the value a user selects in Managers dropdown?

推荐答案

我认为您快到了.我不了解python或flask,但我可以给您主要思想.

I think you're almost there. I don't know python or flask, but I can give you the main idea.

  1. 选择管理器后,您将获得管理器名称,并且必须在ajax调用中发送该名称,因此可以在路由"代码中获取它,并使用它来过滤数组.您可以使用ajax调用的data参数发送该值...

  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'
        });
    });
});

  • 在ajax调用中,创建一个成功回调函数,当您收到成功响应时将调用该函数.像这样...

  • 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) {
                }
            });
        });
    });
    

  • 您还可以添加检查以确认您是否选择了经理或未选中.如果您取消选择经理,则可以清空选择的员工,将其禁用,显示所有员工或您想要的任何内容.

  • 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的了解不足,因此我在帮助您方面遇到困难:

    Now is where I have problems to help you, because of my lack of knowledge of python/flask:

    • 在您的路由代码中,您必须读取与GET ajax调用一起发送的manager参数.我不知道您如何在python/flask中做到这一点,但这必须很容易.在php中只是$_GET['manager'].通过快速搜索,看起来可能像request.GET['username']之类的东西,但是您会比我更好地知道它.您必须获取该参数并将该值放在最后一个返回行中,例如...

    • 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'])
    

  • 我不清楚此回复的格式,因此我不知道如何提取信息以创建员工选择.查看您的ajax调用,您说响应为JSON格式,但是我需要查看该响应的示例以向您展示确切的代码.这个想法是,您必须获取该信息并在ajax调用的成功函数中创建选项,然后将该选项放入员工选择中.像...

  • 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(''));
    }
    

  • 我认为所有这些都可以使您了解如何进行操作,使其适应您的特定需求.希望对您有帮助.

    I think with all this you can have an idea of how to proceed, adapting it to your specific needs. I hope it helps.

    这篇关于使用ajax和jQuery根据烧瓶中第一个下拉列表中选择的值填充第二个下拉列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    相关文章
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆