注意:只列举核心部分代码
前台模板:
第一级下拉菜单:
<div class="col-sm-4"> <select data-placeholder="选择项目..." class="form-control" name="project_id" id="db_link" required="required"> <option value="">请选择数据库连接</option> {% for item in res %} <option value="{{ item.id }}" hassubinfo="true">{{ item.link_name }}</option> {% endfor %} </select> </div>
第二级下拉菜单:
<div class="col-sm-4"> <select data-placeholder="选择基础表." class="form-control" name="project_id" id="db_table" required="required"> // 这里放置回调函数渲染的内容 </select> </div>
对应js:
<script> $("#db_link").change(function() { var options=$("#db_link option:selected"); //获取选中的项 var db_link_id = options.val(); //获取选中的值 {#alert("ok");#} alert(db_link_id); // 选择id=db_link的元素时触发该ajax请求,调用/comparison/get_table接口 $.ajax({ url: '/comparison/get_table', data: {"db_link_id": db_link_id}, type: 'GET', dataType: 'json', success: function (data) { var content=''; {#alert(123456);#} $.each(data, function(i, item){ // 调用接口后返回list数据[u'account_role', u'account_user'],循环遍历该list拼接选项的内容 content+='<option value='+item+'>'+item+'</option>' }); // 将拼接好的内容作为id=db_table这个select元素的内容 $('#db_table').html(content) }, }) }) </script>
视图函数:
def get_table(request): """ 当选择数据库连接时,联动查询出该库的表,供下拉选择 :return: """ if request.method == 'GET': # 获得前台传递来的id,查询对应的数据库连接信息 db_link_id = request.GET.get('db_link_id') print '从前台获得的id为:%s' % db_link_id # 获取数据库类型和数据库名称 db_link_info = LinkDBInfo.objects.get(id=db_link_id) # 当使用model_to_dict时orm只能是get,不能是filter db_link_info_dict = model_to_dict(db_link_info) print db_link_info_dict # 根据不同数据库类型选择不同的连接库方式 if db_link_info_dict['type'] == 'mysql': conn = pymysql.connect(db_link_info_dict['host'], db_link_info_dict['db_username'], db_link_info_dict['db_pwd'], db_link_info_dict['db_name'], charset='utf8') cursor = conn.cursor() # db_name = "select db_name from comparison_linkdbinfo where id='%s'" % db_link_id # print db_name # 查询该库中的所有表 get_all_table_sql = "select table_name from information_schema.tables where table_schema= '%s'" % db_link_info_dict['db_name'] cursor.execute(get_all_table_sql) data = list(cursor.fetchall()) print data table_list = [] for i in data: table_list.append(i[0]) # print data_list print table_list return JsonResponse(table_list, safe=False)