您可以使用AJAX回打电话给你的Django代码,并返回你的车的名称:
template.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(""+data.car+"");
}
});
});
});
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”,如果声明
Django的使用您发送它的ID查询DB执行,返回一辆车
Django将该数据作为JSON对象(本例中是字典)发送回页面
JQuery使用传递的信息更新页面。
如果你想看到一个明确的例子,请参阅本Link