2017-12-02 155 views
0

我有一个很多领域的表格,但我有两个选择,一个选择国家,一个选择我选择的国家的城市。AJAX,Django和HTML选择?

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

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

而不是做一个Ajax调用,你有没有考虑让所有的城市加载客户端在json对象中,并使用普通的javascript来改变你的第二选择的选项? – DragonBobZ

+0

这是一个小提琴https://jsfiddle.net/q4np1169/看起来如何。 (使用jQuery,而不是普通的js) – DragonBobZ

回答

0

我用getJSON代替POST类似的东西。这假设你从HTML中取出onchange,并在jQuery中使用change,而使用select框ID为#countrylist。它使用选择框中的值作为国家/地区的查询id

对于ajax调用,您还需要一个view。 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。让我知道这是否适合你,因为我试图从我自己的文件中转录它。