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条回答 默认 最新

      报告相同问题?

      相关推荐 更多相似问题

      悬赏问题

      • ¥15 有人用过颜色传感器吗?
      • ¥50 求一个SQL长料切短料的优化排版算法
      • ¥15 python 删除TXT文档中小写字母
      • ¥15 ValueError: not enough values to unpack (expected 2, got 0)
      • ¥15 js怎么禁止修改域名
      • ¥15 Cursor为什么在Windows11打不开
      • ¥30 java调用javacv遇到的问题
      • ¥15 如何使用matlab画出带宽100Khz,时长100ms信号的LFM形式的时频图啊
      • ¥15 Error: [BABEL]: Cannot find module '@vue/babel-preset-app'.报错,求解
      • ¥15 --==关于启动加载mount命令的解决方案==--