我正在尝试使用 Django 学习一些基本的 ajax。我的简单项目是一个应用程序,它从数据库中的可用奖品中随机选择一个Prize
,减少其数量,然后返回prize.name
页面。
我正在使用 jQuery 的 $.ajax 方法来解决这个问题。唯一正在运行的是error
我的 $.ajax 调用中定义的函数,但错误消息只显示“错误”。我是 ajax 新手,所以我可能忽略了一些明显的东西。以下是相关代码:
模型
class Prize(models.Model):
name = models.CharField(max_length=50)
quantity = models.IntegerField(default=0)
def __unicode__(self):
return self.name
URLConf
urlpatterns = patterns('',
(r'^get_prize/$', 'app.views.get_prize' ),
)
看法
def get_prize(request):
prizes = Prize.objects.filter(quantity__gt=0)
to_return = {}
if prizes:
rand = random.randrange(len(prizes))
prize = prizes[rand]
prize.quantity -= 1
prize.save()
to_return['prize'] = prize.name
data = simplejson.dumps(to_return)
return HttpResponse(data, mimetype='application/json')
else:
to_return['msg'] = "That's all the prizes. No more."
data = simplejson.dumps(to_return)
return HttpResponse(data, mimetype='application/json')
模板
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>User's Conference Prize Randomizer</title>
<link rel="stylesheet" type="text/css" href="/static-media/style.css" />
<script type="text/javascript" src="/static-media/jquery-1.2.6.min.js"></script>
<script type="text/javascript">
var get_prize = function() {
var args = {
type: "GET",
url: "get_prize",
dataType: "json",
success: done,
error: function(response,error_string,e){
alert( "Error: " + response.responseText + " " + error_string );
for (i in e){
alert(i);
}
}
};
$.ajax(args);
};
var done = function(response) {
if(response) {
alert(response);
}
else {
alert("Something boo-booed");
}
};
$(document).ready(function() {
$("#start").click(get_prize);
});
</script>
</head >
<body>
<p><a href="" id='start'>Get Prize</a>, this link isn't working how I'd like.</p>
</body>