简体   繁体   中英

Get variable value from ajax response

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);

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.

    $.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);

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

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

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

Change

var bill = $(response.cartcount);

To

var bill = response.cartcount;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM