AJAX 调用填充 Select Widget - Python Django

Posted

技术标签:

【中文标题】AJAX 调用填充 Select Widget - Python Django【英文标题】:AJAX call to populate Select Widget - Python Django 【发布时间】:2014-09-17 12:07:14 【问题描述】:

我正在尝试获取 ajax 调用(在 django 中)以根据另一个选定项填充我的网页上的选择框。我是 python、django 和 jquery/javascript 的新手,所以我不太惊讶它不起作用。

我有以下form.py

class InputParametersForm(forms.ModelForm):

sqlConnection = SQLSeverConnection('MSSQLServerDataSource')
tableNames = 
sqlQuery = sqlConnection.getTableNames()

tableNames = tuple((table, table) for table, in sqlQuery)
tableNames = tuple((str(table), str(table)) for table, in sqlQuery)
tableNames = tuple((table.encode(), table.encode()) for table, in sqlQuery)

TableName = forms.ChoiceField(widget=forms.Select(),
                              choices=tableNames)

ColumnName = forms.ChoiceField(widget=forms.Select())

StartDateTime = forms.DateField(widget=SelectDateWidget())

EndDateTime = forms.DateField(widget=SelectDateWidget())

class Meta:
    model = SelectionHistory
    fields = ("TableName", "ColumnName", "StartDateTime", "EndDateTime")

并查看;

def InputParametersView(request):

context = RequestContext(request)
connection = SQLSeverConnection('MSSQLServerDataSource')

if request.method == 'POST':

    pdb.set_trace()

    if form.is_valid():
        form.save(commit=True)

        ChartData.objects().all().delete()
        this_XData = connection.getColumnData('DateTimeStamp', SelectionHistory.TableName[0], SelectionHistory.StartDateTime[0], SelectionHistory.EndDateTime[0])
        this_YData = connection.getColumnData(SelectionHistory.ColumnName[0], SelectionHistory.TableName[0], SelectionHistory.StartDateTime[0], SelectionHistory.EndDateTime[0])
        ChartData.XData = this_XData
        ChartData.YData = this_YData

        ChartData.save()

elif request.method == 'GET':

    pdb.set_trace()

    if request.is_ajax():

        pdb.set_trace()

        selected_table = request.GET['selected_table']
        columns = connection.getColumnTitles(selected_table)

        column_names = 
        column_names = tuple((column, column) for column, in columns)
        column_names = tuple((str(column), str(column)) for column, in columns)
        column_names = tuple((column.encode(), column.encode()) for column, in columns)

        return HttpResponse(column_names)

    return render_to_response('input_parameters-ajax.html', 'form': InputParametersForm,  context)

以及以下模板 - 包含脚本;

<html>

    % load staticfiles %

    <title>Input Parameters</title>

    <script src="% static 'dgconnection/js/jquery-2.1.0.min.js' %"></script>
    <script src="% static 'dgconnection/bootstrap/js/bootstrap.min.js' %"></script>

    <script>

        $("#id_TableName").change(function()
        
            tableSelectionChanged();
        )

        function tableSelectionChanged()
        
            var selected_table = $("#id_TableName").selectedIndex;
            $.get('/historicaldata/input_parameters/', selected_table : selected_table, function(column_names)
            $("#id_ColumnName').val(column_names);
            );
        

    </script>

<body>
    <h1>What would you like to see?</h1>

    <form id="input_parameters" method="post" action="http://127.0.0.1:8000/historicaldata/chart_view/">
        % csrf_token %
        <ul>
            form.as_ul
        </ul>

        <input type="submit" value="submit" />
    </form>

</body>

我得到以下网页,更改顶部后,下方的选择框没有任何内容;

【问题讨论】:

【参考方案1】:

我认为您的 ajax 结构不正确。首先,我会使用 jquery,并将 ajax 放在一个块中。 下面是一个例子,说明我做了你正在做的同样的事情。

http://munitag.herokuapp.com/

因此,当有人选择巴士站时,它会添加该特定巴士站的停靠站选项。

HTML

        <form role="form">
         <div class="form-group">
            <select id = "stop"class="form-control input-lg">
        <option>Please select a route</option>
                % for x in stops %
                <option >x</option>
                % endfor %

            </select>
              <select style="";"id ="stoplist" class="form-control input-lg"> </select>
          <select style="display:none;"id ="direction" class="form-control input-lg"> 
          <option>Inbound</option>
          <option>Outbound</option>
          </select>

     <button type="button" id = "tagbutton"  style="display:none;"onclick= "myFunction()"  class="btn btn-info navbar-btn">Tag</button>
      </div>
        </form>\

那么对于ajax

% block postscript %

<script type="text/javascript">

 $(document).ready(function() 
  $("#stop").change(function()
    document.getElementById("stoplist").style.display ="block";
    document.getElementById("tagbutton").style.display ="block";
    document.getElementById("direction").style.display ="block";

      $.ajax(
          type: 'POST',
          data:  keyname:$('#stop option:selected').val(),
           success: function(resp)
            for (var i=0; i < resp['routestops'].length;++i)

              addOption(document.getElementById("stoplist"), resp['routestops'][i], resp['routestops'][i]);
            

             

      );
  );
); 

 </script>

% endblock postscript %

jquery 正在处理成功的发布响应,它是一个停止列表,并且正在使用 AddOption 函数将这些选项添加到选择元素。

这是当有人选择一个选项并更改目标元素时处理 ajax 的视图

if request.is_ajax():


    stop = request.POST.values()[0]

    routestops = stops[stop]['stops']
    r = 'routestops':routestops


    return HttpResponse(json.dumps(r), mimetype="application/json")
else:

    return render(request, 'muni/home.html', payload)

【讨论】:

以上是关于AJAX 调用填充 Select Widget - Python Django的主要内容,如果未能解决你的问题,请参考以下文章

动态填充 select2 下拉列表

用数据库中的值填充select标签[关闭]

Jquery .change() 函数不适用于动态填充的 SELECT 列表

使用 AJAX 数据填充 Select2

select2 4.0 AJAX 预填充如何?

使用 AJAX 预填充 Select2 - “未找到结果”