简体   繁体   中英

Jquery Not picking data from an existing array with data

I have a piece of code that retrieves the last question on a program and it is suposed to update the values of HTML5 progress bars with the latest values.

Now for some reason that I cannot find, when I console.log the data parameter, it is full. But when I try to use it nothing is shown.

Is there something wrong in the code that I cannot realize?

在此处输入图片说明

//Run timer
$(document).ready(function () {
    if($('input[name=active_question]').val()!="")
    {
        start_timer();
    }
});
function start_timer()
{
   var x=0;
    function doStuff() {
       x++;
       $('.timer').html(x+' sec');
       console.log('Timer:'+x);
       $.ajax({
        method: "GET",
        url: "/services/get_active_question/"
        })
        .done(function( data ) {
            //It is time to regenerate the question values.
            console.log('Data:'+data);
            if(data['id']!=0)
            {
                regenerate_question(data);
            }
        });
    }
    setInterval(doStuff, 1000); 
}
function regenerate_question(data)
{
    if(data['id']!=0)
    {
        console.log('A: '+data['a']);
        $('.progress-a').prop('value',data['a']);
        $('.progress-b').prop('value',data['b']);
        $('.progress-x').prop('value',data['x']);
        $('.progress-y').prop('value',data['y']);
    }
}

Your return from the ajax is json string. But the ajax is not identifying it as JSON. So you'll need to specify the dataType as JSON .

$.ajax({
    method: "GET",
    url: "/services/get_active_question/",
    dataType: 'json'
}).done(function( data ) {
    //It is time to regenerate the question values.
    console.log('Data:'+data);
    if(data['id']!=0)
        regenerate_question(data);
});

Alternative way is to use

data = JSON.parse(data) 

in the done function.

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