【发布时间】:2020-08-31 15:26:14
【问题描述】:
我试图从我的 javascript 函数内部调用两个视图,它们是增量和减量,它们应该更改我的一个模型中的值。除了请求(数量)之外,这两种观点都有另一个论点。我认为让这个系统工作的最好方法是通过 ajax,但我不知道如何使用多个参数进行调用。
这是我的javascript
$('#redButton').click(function (e) {
var amount = $("#amount").val();
var totalCoins = "{{ user.profile.coins }}";
if(amount <= totalCoins && amount > 0)
{
//decrement total coins by amount
var choice = 0;
spinWheel(choice, amount);
}
return false;
});
$('#blackButton').click(function (e) {
var amount = $("#amount").val();
var totalCoins = "{{ user.profile.coins }}";
if(amount <= totalCoins && amount > 0)
{
//decrement total coins by amount
var choice = 1;
spinWheel(choice, amount);
}
return false;
});
$('#greenButton').click(function (e) {
var amount = $("#amount").val();
var totalCoins = "{{ user.profile.coins }}";
if(amount <= totalCoins && amount > 0)
{
//decrement total coins by amount
var choice = 2;
spinWheel(choice, amount);
}
return false;
});
function spinWheel(choice, amount){
e.preventDefault();
stoping = false;
// Random between 1 and 10
var itemSelected = Math.floor((Math.random() * 11));
var $jump = $(this);
//$jump.html('Jumping ...');
$jump.attr('disabled', 'disabled');
// Trigger autoplay owl
$owl.trigger('play.owl.autoplay', [100]);
// Slow speed by step
setTimeout(slowSpeed, 2000, $owl, 200);
setTimeout(slowSpeed, 4000, $owl, 250);
setTimeout(slowSpeed, 5000, $owl, 300);
setTimeout(stopAutoplay, 6000);
if(choice == 0)
{
if(itemSelected != 0 && itemSelected % 2 == 0)
{
amount = amount * 2;
//Call ajax function to increment by amount
}
}
else if(choice == 1)
{
if(itemSelected != 0 && itemSelected % 2 != 0)
{
amount = amount * 2
//Call ajax function to increment by amount
}
}
else if(choice == 2)
{
if(itemSelected == 0)
{
amount = amount * 6;
//Call ajax function to increment by amount
}
}
return false;
}
这是我的 Django 视图
@login_required
def Decrement(request, amount):
profile = get_object_or_404(Profile, user=request.user)
if amount <= profile.coins:
profile.coins -= amount
profile.save(update_fields=['coins'])
else:
#change this later to return an error
return HttpResponse('')
profile.coins -= amount
return HttpResponse('') #return void
@login_required
def Increment(request, amount):
profile = get_object_or_404(Profile, user=request.user)
profile.coins += amount
profile.save(update_fields=['coins'])
return HttpResponse('') #return void
谢谢!
【问题讨论】:
标签: javascript jquery django ajax django-views