现在我需要制作一个拥有自己游戏的网站。目前一切正常,但我需要知道如何将高分存储到 django 模型中。
我的想法是一个隐藏的POST表单,它会自动触发(目前甚至手动就足够了),然后它只是通过POST表单将存储在JavaScript变量中的整数提交给模型。
我将为您提供我当前的代码片段,这样您就会知道我走了多远以及我正在接近什么。
views.py
def loadGame(request, slug):
game = Game.objects.get(slug=slug)
if request.method == 'POST':
pass
return render(request, 'main/game-detail.html', {
'game': game
})
模板中我的隐藏表单
<form action="/games/{{ game.slug }}" method="post">
{% csrf_token %}
<button type="submit" hidden>Upload your highscore to the Leaderboard?</button>
</form>
排行榜的models.py模型
class Ranking(models.Model):
player = models.ForeignKey(User, on_delete=models.CASCADE)
game_overall_score = models.IntegerField(null=True)
var score = 0;
...
if (pipes[i].hits(bird)) {
score = 0;
pipes = [];
return;
}
...
if (frameCount % 5 == 0) {
score++;
}
我真的不知道从哪里开始。我用 jQuery 或 AJAX 查找了多种方法,但没有人遇到像我一样的情况,我真的只需要存储一个整数,然后将自动分配用户
我觉得你想太多了。我尽可能避免提交表单数据。依靠 JQuery 及其简单的事件处理。我不确定你是如何获取用户名的,但我只是在其中添加了一个字段。否则,只需获取变量即可。
<!--HTML -->
<input type="text" id="player-name">
<button id="submit-score">Upload your score</button>
<!--Javascript-->
<script>
var score = 0
// Your score counting stuff
$("#submit-score").on("click", function(){
data={}
data['game_overall_score'] = score
data['player'] = $("#player-name").val()
$.ajax({
url: "...",
type: "POST",
contentType: "application/json",
data: JSON.stringify(data),,
success: function(){
//do whaterever you want here
}
})
})
</script>