简体   繁体   中英

jQuery ajax post success - saving data to variable

I have this function:

function getReport(name,x) {
    var xArr = [];
    var yArr = [];
    $.ajax({
        async: false,
        type: "POST",
        //async: false,
        //dataType: "json",
        url: "reportAjax.php",
        data: "name="+ name,
        success: function(data){
            var json = $.parseJSON(data);
            var chartDesc = json.INFO.DESC;
            $.each(json.RESULT, function(i, object) {
                $.each(object, function(property, value) {
                    //alert(property + "=" + value);
                    if (property == x) {
                        xArr.push(value);
                    }
                    else {
                        yArr.push(parseInt(value));
                    }

                });
            });                
        }
    }); 
    console.log(xArr);
    console.log(yArr);
    console.log(chartDesc);
    drawChart(xArr,yArr,chartDesc);
}

For some reason, I can see in the console.log the values of xArr and yArr , but I get chartDesc is not defined for chartDesc .

If I move the console.log(chartDesc) line to be under this line var chartDesc = json.INFO.DESC I can see it properly.

Why is that?

You are declaring the chartDesc variable inside the AJAX callback function, so it is outside the scope of your later reference to it.

To fix this, remove the var from the start of the line, and instead declare it at the top of the function with the xArr and yArr variables:

var xArr = [];
var yArr = [];
var chartDesc = "";

chartDesc variable scope is tied to the success function, that's why outside it, the variable is undefined . in Javascript functions create scopes for variables defined with var

make your

console.log(xArr);
console.log(yArr);

within success function. and declire chartDesc variable outside of success function,

console log outside of success function execute immediately when function called, but it takes some time to insert value of xArr and yArr due to success function execution. so you get nothing in you log.

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