2017-12-02 154 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。讓我知道這是否適合你,因爲我試圖從我自己的文件中轉錄它。