[英]populate a select box from a another select box and using database connection
I have two select boxes: one is country and the other one is cities. 我有两个选择框:一个是国家,另一个是城市。 When the user selects a country, the appropriate cities for that country should be populated in the "cities" from the database. 当用户选择一个国家时,应该在数据库的“城市”中填充该国家的适当城市。
I am new to jquery and javascript and i am not sure how to implement this. 我是jquery和javascript的新手,我不确定如何实现此功能。 It will be appreciated if someone gives me a sample code for performing this functionality. 如果有人给我示例代码来执行此功能,将不胜感激。 I have no idea and i am pretty much stuck as i am new to the scripting languages. 我不知道,因为我是脚本语言的新手,所以我非常困惑。
I am using this in one of my forms in django framework which is implemented in python. 我正在以Django实现的一种形式在Django框架中使用它。
Thank you in advance 先感谢您
<!DOCTYPE html>
<html>
<head>
<style>
div { color:red; }
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<select name="country" id="country">
<option value = "india">india</option>
<option value = "USA">USA</option>
<option value = "UK">UK</option>
<option value = "China">China</option>
<option value = "Sweden">Sweden</option>
<option value = "Germany">Germany</option>
</select>
<select name="cities" id="cities">
<option value = ""></option>
</select>
<div></div>
</body>
</html>
Try this: 尝试这个:
In your template 在您的模板中
$('#country').change(function() {
var value = $(this).attr('value');
var request = $.ajax({
url: "/getcities/",
type: "GET",
data: {country : value},
dataType: "json",
success: function(data) {
//Popluate combo here by unpacking the json
}
});
});
In your view: 您认为:
def getcities(request)
if request.method == "GET":
country = request.GET["country"]
cities = Cities.objects.filter(country=country)
results = [{'city': str(city.name), 'id':city.id} for city in cities]
json = simplejson.dumps(results)
return HttpResponse(json, mimetype='application/json')
You will have to map the url /getcities/ to your view in urls.py. 您必须将url / getcities /映射到urls.py中的视图。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.