简体   繁体   中英

Code after $.post() is executed before post-request is finished

I am trying to get data from a server using a post request (jQuery's $.post) and assign it to a JavaScript variable.

The code is as follows:

function getData() {        
    var zones = DUMMY_zones;
    var workers = [];

    console.log("1");

    $.post('server/main.php', {info: 'req_workers'}, function(result) {
        var result = JSON.parse(result);

        console.log("2");

    });


    console.log("3");
    return [zones, workers];
}

Yet strangely, the return is executed before the $.post request finsihes, so that workers is undefined variable. The console output is as follows:

ppe_c_js.js:82 1
ppe_c_js.js:90 3
ppe_c_js.js:85 2

How can I execute the code sequentially?

Thank you!

You can make the jquery post synchronous . but this is a bad practice. so, your browser will be in freezing state during the operation.

 $.ajax({ type: 'POST', url: url, data: data, success: success, dataType: dataType, async:false }); 

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