嗯,有很多方法可以实现,但我在这里举一个简单的例子
以网址开头:
url(r'^end-game/?','your_app.views.end_game', name='end-game'),
然后在 your_app.views 上
import datetime
from django.http import HttpResponse
from django.contrib.auth.decorators import login_required
from your_app.models import Game
@login_required(redirect_field_name=None, login_url='login')
def end_game(request):
# Get the post variables
score = request.POST['score']
win = request.POST['win']
# You may want to validate data here
# Create the game object
try:
game = Game.objects.create(
user = request.user.id,
score = score,
win = win,
date = datetime.datetime.now()
)
game.save()
# Setting output
response = {
'status': 1,
'message': 'Game saved'
}
except Exception as e:
# Something went wrong
response = {
'status': 0,
'message': 'Something went wrong - ' +str(e)
}
return HttpResponse(response, mimetype='application/json')
javascript(在 html 文件中):
$.post( "{% url 'end-game' %}",
{
csrfmiddlewaretoken: '{{ csrf_token}}' ,
score : score, //pass the score here
win: win // pass the win value here
},
function(data) {
if(data.status == 1){
// success! Do something
}
else{
// error! Do something
}
});
您也可以使用表单,将其隐藏并在游戏结束时提交。这样做有一些好处,比如表单本身有验证和保存功能,但是由于您只需要两个变量,上面应该没问题。
另外,你应该使用类似的东西
if request.method is POST:
在你做任何事情之前,在尝试读取它们之前检查是否设置了 POST 值......
if 'score' in request.POST:
这只是示例,未经测试,但应该可以正常工作