从temp将变量保存到Django后端的简单ajax请求

2024-10-04 01:23:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我在UserProfile模型中有score字段。以及jquery中的变量total。 我想在点击“提交”按钮后,在“得分”字段中存储总计的值。 我想让ajax来做这件事。在

在这里我尝试了一些东西。在

$('#myButton').click(function(){
    var bjpFan=localStorage['bjpFan'];
    var total = parseInt(localStorage['total']);
    $.ajax({
      url: "/poll/score/",
      type:"GET",
      success: function(responseHTML){
       {% for sc in score1 %}
           var s={{sc.score}}
           alert(s);
       {% endfor %}
      }
    });
}); 

现在我想在后台保存价值。如何保存这个值。在

在视图.py在

^{pr2}$

在模型.py是

class UserProfile(models.Model):
    user = models.ForeignKey(User) 
    score = models.IntegerField(max_length = 50, blank = True,null = True)

希望将total存储为score,,,,但total是jquery中声明的变量


Tags: py模型truemodelsvarajaxfunctionjquery
1条回答
网友
1楼 · 发布于 2024-10-04 01:23:08

试试这个方法:

您的html:

$('#myButton').click(function(){
  var bjpFan=localStorage['bjpFan'];
  var userid = //get your user id in some way you can
  var total = parseInt(localStorage['total']);
  $.ajax({
    url: "/poll/score/",
    type:"GET",
    data: {total:total,userid:userid}
  }).done(function(data){
     alert(data);//do what you want to do with response
  });
}); 

你的网址.py公司名称:

^{pr2}$

你的py.py视图在

def score(request):
   if request.is_ajax():
     if request.method == 'GET':
        user = UserProfile.objects.get(id=request.GET.get('userid'))
        user.score = request.GET.get('total')
        user.save()
        return HttpResponse("%s" % user.score )

就这样。在

相关问题 更多 >