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 MATLAB怎么通过柱坐标变换画开口是圆形的旋转抛物面?
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿