您可以使用 AJAX 回调您的 Django 代码并返回您的汽车名称:
模板.html
$(document).ready(function () {
$(document).on("click",'.car_add', function() {
$car_id = $(this).attr('id')
$.ajax({
type: "POST",
// This is the dictionary you are SENDING to your Django code.
// We are sending the 'action':add_car and the 'id: $car_id
// which is a variable that contains what car the user selected
data: { action: "add_car", id: $car_id },
success: function(data){
// This will execute when where Django code returns a dictionary
// called 'data' back to us.
$("#car").html("<strong>"+data.car+"</strong>");
}
});
});
});
views.py
def post(self,request, *args, **kwargs):
if self.request.is_ajax():
return self.ajax(request)
def ajax(self, request):
response_dict= {
'success': True,
}
action = request.POST.get('action','')
if action == 'add_car':
car_id = request.POST.get('id','')
if hasattr(self, action):
response_dict = getattr(self, action)(request)
car = CAR.objects.get(ida_name='car_id')
response_dict = {
'car_name':car.name
}
return HttpResponse(simplejson.dumps(response_dict),
mimetype='application/json')
总而言之,这就是您正在做的事情:
- 通过 Ajax 将汽车的“id”发送回 Django。
- Django“发布”给自身,意识到这是一个 AJAX 调用并调用 AJAX 函数
- Django 看到操作是“add_car”并执行 if 语句
- Django 使用您发送的 ID 查询数据库,返回一辆车
- Django 将该数据作为 JSON 对象(在本例中为字典)发送回页面
- JQuery 使用传递的信息更新页面。
如果您想查看清晰的示例,请参阅此Link http://www.devinterface.com/blog/en/2011/02/how-to-implement-two-dropdowns-dependent-on-each-other-using-django-and-jquery/