从ajax响应中获取变量值

时间:2018-05-19 22:30:39

标签: javascript jquery json ajax

我有以下ajax请求,它返回一个json对象(我​​认为)。当我读取console.log(response);

的结果时,你可以看到cartcount的值

我想将var bill设置为等于cartcount的值,在下面的示例中等于“1”。我尝试了很多方法,但我怀疑我对json有误解。

    $.ajax({
        url: app_config.ajax_cart_add,
        type: 'POST',
        data: data,
        dataType: "json",
        beforeSend: function() {
        },
        success: function(response) {
            if (response.success === true) {

                console.log(response);

                var bill = $(response.cartcount);
                console.log(bill);

                App.success('Item was successful.');           
            }
            if (response.success === false) {
                App.error('There was a proble');
            }
        }
    });

我的控制台日志为console.log打印(响应);

{success: true, cartcount: "1"}
    cartcount:"1"
    success:true

    proto:Object
        a bunch of stuff in the proto object that seems irrelevant to my question.

1 个答案:

答案 0 :(得分:3)

不要将数据包装在$()中。它正在创建一个不必要的jQuery对象

更改

var bill = $(response.cartcount);

var bill = response.cartcount;