weixin_33738578 2017-12-02 17:22 采纳率: 0%
浏览 127

AJAX,Django和HTML Select?

I have a form with many fields, but I have two selects, one for select the country and one for select the cities of the country that I selected.

I want to make this: When I choose the country in the first select I want to change the cities of the second select filtered by the id of the contry that I selected.

Here is my Models.py

class country(models.Model):
    country_name = models.CharField(max_length=264)
    def __str__(self):
        return self.country_name

class country_cities(models.Model):
    city_name = models.CharField(max_length=264)
    country = models.ForeignKey(country)
    def __str__(self):
        return self.city_name

And Here is my HTML Form:

<form method="post">
  <input type="text" name="username">
  <select name="country" onchange="listCities()">
    {% for country in countrylist %}
      <option value="{{ country.id }}">{{ country.country_name }}</option>
    {% endor %}
  </select>
  <select name="city" id="citylist">
    <!--HERE IS WHERE I WANT TO LIST JUST THE CITIES OF THE COUNTRY THAT I SELECTED-->

  </select>
</form>

How do I make my view and what libraries I have to import in my views.py? Also I'm not sure if my AJAX library or my script is correct.

AJAX:

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>

SCRIPT:

<script type="text/javascript">
  function listCities()
  {
    var countryid = $("[name='country']").val();
    $('#citylist').html('');
    $.ajax({
      type: "POST",
      data: "countryid="+countryid,
      url: "editprofile/",
      success: function(result)
      {
        var resultObj = JSON.parse(result);
        var dataHandler = $("#citylist");
        $.each(resultObj, function(key, val)
        {
            var newRow = $('<option value="'+val.id+'">');
            newRow.html(' '+val.city_name +'');
            dataHandler.append(newRow);
        });

      }
    });
  }
</script>
  • 写回答

1条回答 默认 最新

  • 狐狸.fox 2018-03-09 09:52
    关注

    I used getJSON instead of POST for something similar. This assumes that you take out onchange from HTML and use change within jQuery instead, with a select box ID of #countrylist. It uses the value from the select box as the lookup id for country.

    You'll need a view for the ajax call, too. The url variable in the AJAX portion will hook to that. Your views.py and script.js could have something like this:

    #views.py
    #...other imports...
    from django.core import seralizers
    
    def select_country(request):
      if request.method == 'GET' and request.is_ajax():
        selected_country = request.GET.get('id')
        json_city = serializers.serialize("json", country_cities.objects.filter(country_id = selected_country))
        return HttpResponse(json_city, content_type='application/json')
      else:
        return HttpResponse("no-go")
    
    #YourScript.js
    $(function(){
    //...your AJAX configurations would go up here, like CSRF stuff...
    
    $(document).on('change', "#countrylist", function(e) {
        e.preventDefault();
        console.log($(this).val());
        var url = http://127.0.0.1:8000/yourURLtoView
        $.getJSON(url, {id: $(this).val()}, function(j) {
            var options = '<option value="">---??---</option>';
            for (var i = 0; i < j.length; i++) {
                options += '<option value="' + parseInt(j[i].pk) + '">' + j[i].fields['city_name'] + '</option>';
            }
            console.log(options); //This should show the new listing of filtered options.
            $("#citylist").html(options);
            $("#citylist option:first").attr('selected', 'selected');
        });
        $("#countrylist").attr('selected', 'selected');
    });
    
    });
    

    Also, if I might recommend that you rename your country_cities model to just City. Imagine classes as a proper Entity, like Car or Person or Computer. Let me know if this works for you, as I tried to transcribe it from one of my own files.

    评论

报告相同问题?

悬赏问题

  • ¥15 mindspore项目_模型适配
  • ¥15 openstack使用cinder后,实例运行时分配的总空间不能大于ceph的总空间
  • ¥15 [pcl::PLYWriter::writeASCII] Error during opening (?鶂?)!
  • ¥15 得到XY两轴的数据如何绘制成圆,输入整形器
  • ¥29 PHP读取PDF文件添加多个数字签名
  • ¥25 联邦学习vgg修改最后一个全连接层报错(默认是1000个输出,我的改为11就报错,改为200就没问题)
  • ¥15 maple画图问题,为什么会是这样
  • ¥15 RC522开发arduino作品刷卡失效
  • ¥15 comsol仿真频域研究以及结果处理
  • ¥15 Js 中Ajax的get方式请求,电文头怎么写