我在UserProfile模型中有得分字段。和jquery中的变量总和。 我想在点击提交按钮后存储得分字段中的总值。 我想为此做一个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 %}
}
});
});
现在我想在后端节省价值。如何保存单个值。
view.py
def score(request):
if request.is_ajax():
if request.method == 'GET':
score1=UserProfile.objects.all()
print "akash"
print score1
print type(score1)
response = json.dumps({"SCORE":score})
return HttpResponse(response,mimetype="application/json")
model.py是
class UserProfile(models.Model):
user = models.ForeignKey(User)
score = models.IntegerField(max_length = 50, blank = True,null = True)
想要将总数存储到得分,,,,但是total是在jquery中声明的变量
答案 0 :(得分:1)
尝试这种方式:
你的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
});
});
你的urls.py:
url(r'/poll/score/$', 'score', name='score'),
你的views.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 )
就是这样。