我有一个包含很多字段的表单,但我有两个选择项,一个用于选择国家,一个用于选择我选择的国家/地区的城市。
我想这样做:当我在第一个选择中选择国家时,我想更改第二个选择的城市,该城市由我选择的国家的 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.py
和 script.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
.将类想象成一个合适的实体,比如 Car
或 Person
或 Computer
.让我知道这是否适合你,因为我试图从我自己的一个文件中转录它。
关于javascript - AJAX、Django 和 HTML 选择?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47610505/