【问题标题】:AJAX, Django and HTML Select?AJAX、Django 和 HTML 选择?
【发布时间】:2018-05-16 13:39:43
【问题描述】:

我有一个包含许多字段的表单,但我有两个选择,一个用于选择国家,一个用于选择我选择的国家/地区的城市。

我想做这个:当我在第一个选择中选择国家时,我想更改第二个选择的城市,由我选择的国家的 id 过滤。

这是我的 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

这是我的 HTML 表单:

<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>

如何制作视图以及必须在 views.py 中导入哪些库?另外我不确定我的 AJAX 库或脚本是否正确。

AJAX:

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</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>

【问题讨论】:

  • 您是否考虑过将所有城市加载到 json 对象中的客户端并使用纯 JavaScript 更改第二次选择中的选项,而不是进行 Ajax 调用?
  • 这是一个小提琴jsfiddle.net/q4np1169,它的外观。 (使用 jquery,而不是普通 js)

标签: javascript jquery python ajax django


【解决方案1】:

我用getJSON 代替POST 来做类似的事情。这假设您从 HTML 中取出 onchange 并在 jQuery 中使用 changeselect 框 ID 为 #countrylist。它使用选择框中的值作为国家/地区的查找 id

您还需要一个 view 来进行 ajax 调用。 AJAX 部分中的url 变量将与之挂钩。你的views.pyscript.js 可能有这样的东西:

#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');
});

});

另外,如果我建议您将 country_cities 模型重命名为 City。将类想象成一个适当的实体,例如 CarPersonComputer。让我知道这是否适合您,因为我试图从我自己的一个文件中转录它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-25
    • 2023-02-22
    • 2021-09-26
    • 2015-08-28
    • 2011-07-22
    • 1970-01-01
    相关资源
    最近更新 更多