JavaScript:JSON条件基于用户响应

时间:2017-08-24 10:02:44

标签: javascript jquery json

这让我发疯了。

用户点击按钮进行预约。 AJAX根据预订是否成功返回一个值:预订成功,清除旧预订或被阻止,因为有人已预约。该值将返回到视图,按钮会根据用户的选择而更改。

我已经尝试了所有可能的迭代,但它不起作用。即使console.log表示值== 1,JS也不会承认该值== 1,而且我每次都会收到错误消息。

views.py
@ensure_csrf_cookie
def reserve(request):
    if request.is_ajax():
        pk = request.POST['pk']
        slot = Event.objects.get(pk=pk)
        user = request.user
        if slot.is_reserved == True:
            if user == slot.teacher:
                slot.is_reserved = False
                slot.teacher = None
                slot.save()
                result = "1"
            else:
                result = "3"
        else:
            slot.is_reserved = True
            slot.teacher = user
            slot.save()
            result = "2"
    data = {'result': result}
    return HttpResponse(json.dumps(data, cls=DjangoJSONEncoder))

//main.js
$( document ).ready(function() {
      var count = 0; //to reload the page
      console.log( 'ready!' + count ); //Sanity check
      $( 'button' ).click(function() {
        var pk = this.id
        var user = $( 'button' ).attr("user")
        $.ajax({
            url: "/reserve/",
            type: "POST",       //Send the info to view
            data: { pk : pk},
            success: function(data) {
           var number = JSON.parse(data);
        if (number == 1 ) {
            $(this).toggleClass( "free reserved" );
            $.toast({
                heading: "Reservation Clear!",
                icon: 'success',
                stack: 4,
                hideAfter: 2000,
                bgColor: '#003366'
                    });
            }
        if (number == 2) {
             $(this).toggleClass( "free reserved" );
             $("div.tchr").html(user);   //Send user info to button, reverts on refresh
                $.toast({
                    heading: "Reservation Complete!",
                    icon: 'success',
                    stack: 4,
                    hideAfter: 2000
                });
        }
        if (number == 3) {
            alert("Sorry! This has already been reserved (maybe refresh your browser)")
                    }
        else {
        console.log("Something is wrong. Something is wrong. Something is wrong")
                                        }
        count++;
        console.log(count)
        if (count > 3) {
               location.reload();
               };
               }
           }); // End AJAX
        });
});

我尝试过在两端使用引号,JSON.Stringify,甚至创建一个与字典完全相同的var。救命啊!

3 个答案:

答案 0 :(得分:2)

您创建

data = {'result': result} 

然后解析它

var number = JSON.parse(data);

这意味着数据包含{"result": yourvalue}

您可以number.resultnumber['result']

访问它

此外,您在javascript正在检查整数值的响应中返回字符串

答案 1 :(得分:0)

使用typeof()查找返回的数据类型,然后添加条件检查。

 var number = JSON.parse(data);
console.log(typeof(number)) // check this what is the output and add the condition based on it
            if (number == 1 ) {

答案 2 :(得分:0)

1)首先使用typeof()运算符检查解析后的号码。

console.log(typeof(number));

2)如果是阵列,那就试试吧。

number[0] == 1