从ajax响应中获取变量值

时间:2022-01-14 20:17:15

I have the following ajax request which returns a json object (I think). You can see the value of cartcount when I read the results of console.log(response);

我有下面的ajax请求,它返回一个json对象(我认为)。当我阅读console.log(response)的结果时,您可以看到cartcount的值;

I want to set var bill equal to the value of cartcount, which equals "1" in the below example. I have tried a variety of ways, but I suspect I am misunderstanding json.

我想设置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');
            }
        }
    });

What my console log prints for console.log(response);

consolel .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 个解决方案

#1


3  

Don't wrap the data in $(). It is creating a needless jQuery object

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

Change

改变

var bill = $(response.cartcount);

To

var bill = response.cartcount;

#1


3  

Don't wrap the data in $(). It is creating a needless jQuery object

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

Change

改变

var bill = $(response.cartcount);

To

var bill = response.cartcount;