JSON数据解析不起作用

时间:2016-04-23 09:41:15

标签: javascript html json

伙计们请参阅下面的Javascript代码:

$(document).ready(function () {
$('.loader').hide();
getDataUsers("userCount");
var obj = JSON.parse($("#hdUserCount").val());
userChart(obj.Actives, obj.InActives, obj.Discountinued, obj.recentlyJoined);
});
function userChart(act, inact, disc, recent) {
var chart = new CanvasJS.Chart("userChart", {

                                   title: {
        text: "Users"

    },
                                   animationEnabled: true,
                                   axisX: {
        interval: 1,
        gridThickness: 0,
        labelFontSize: 10,
        labelFontStyle: "normal",
        labelFontWeight: "normal",
        labelFontFamily: "Lucida Sans Unicode"

    },
                                   axisY2: {
        interlacedColor: "rgba(1,77,101,.2)",
        gridColor: "rgba(1,77,101,.1)"

    },

                                   data: [{
                                               type: "bar",
                                               name: "Users",
                                               axisYType: "secondary",
                                               color: "#014D65",
                                               dataPoints: [

                                                   { y: act, label: "Active" },
                                                   { y: inact, label: "InActive" },
                                                   { y: disc, label: "DisContinued" },
                                                   { y: recent, label: "Recently Joined" },
                                               ]
                                           }

    ]
                               });

chart.render();
}
function getDataUsers(flagData) {
$('.loader').fadeIn('fast');
$.post("Stats.ashx", {
           flag: flagData,
       }, function (data, status) {
           $("#hdUserCount").val(data);
           $('.loader').fadeOut('fast');
           alert(data);
       });
}

问题是当它在FireBug中以调试模式运行而第3行到第5行有断点时没有问题,而且每件事情都很好。 但!当我删除断点时,我认为代码的某些部分没有被执行!有线!!!我认为解析JSON数据的部分不起作用!!!

这是通过邮寄收到的数据:

  

{" Actives":3," InActives":4," Discountinued":0,"最近加入":6}

1 个答案:

答案 0 :(得分:1)

这不是异步代码的工作方式。这就是你的功能应该是这样的:

function getDataUsers(flagData, callback) {
    $('.loader').fadeIn('fast');
    $.post("Stats.ashx", {
           flag: flagData,
           }, function (data, status) {
               callback(data);
           }
     });
 }

然后你称之为:

getDataUsers('userCount', function(data) {
      $("#hdUserCount").val(data);
      $('.loader').fadeOut('fast');
      var obj = JSON.parse($("#hdUserCount").val());
      // Add the rest of code that relies on obj .. 
}