javascript - AJAX、Django 和 HTML 选择?

标签 javascript jquery python ajax django

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

我想这样做:当我在第一个选择中选择国家时,我想更改第二个选择的城市,该城市由我选择的国家的 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>

如何创建 View 以及必须在 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>

最佳答案

我用了getJSON而不是 POST对于类似的东西。这假设您取出 onchange来自 HTML 并使用 change相反,在 jQuery 中,使用 select #countrylist 的盒子 ID .它使用选择框中的值作为查找 id为国家。

你需要一个 view对于ajax调用也是如此。 url AJAX 部分中的变量将 Hook 到它。你的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 .让我知道这是否适合你,因为我试图从我自己的一个文件中转录它。

关于javascript - AJAX、Django 和 HTML 选择?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47610505/

相关文章:

python - 如果满足 'if' 条件,是否有办法增加迭代器

python - numpy 中的累积分布函数未达到 1?

javascript - RequireJS:加载库模块后自动加载配置脚本

javascript - jQuery 使用#/page 获取页面

javascript - 在 jQuery UI Datepicker 中为选定的日期添加一个特殊类

javascript - 将 json 绑定(bind)到 DOM

javascript - 如何在 AngularJS 中使用 jQuery

jquery 图片库无法正常工作

python - FFT:查找并消除信号中的噪声 50Hz

javascript - SetData() 不适用于更改事件 HighCharts 饼图