AJAX调用填充Select Widget - Python Django

时间:2014-07-25 15:18:40

标签: jquery ajax django django-templates django-ajax-selects

我试图获取一个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>

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

nothing in columnname select..

1 个答案:

答案 0 :(得分:0)

我认为你没有正确构建你的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正在处理成功的post响应,它是一个停止列表,并使用AddOption函数将这些选项添加到select元素。

这是当有人选择一个选项并更改目标元素时处理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)