简体   繁体   中英

Wordpress ajax with async false

Inside WordPress, I want to use ajax return value outside the function

Example

function get_login_member($) {
    $.post(ajax_object.ajax_url, {action: 'getloginmember'}, function (data) {
            data = JSON.parse(data);

            if (data['id'] > 0) {
                return data;
            } else {
                return 0;
            }
    });
}

And this function calling from

var row = get_login_member($);

The row variable is undefined because it executes before ajax request success

With Jquery ajax this can be done by made async:false

Is there any way to do this inside WordPress

forget sycnhronous ajax - easiest solution is to use a callback

function get_login_member($, cb) {
    $.post(ajax_object.ajax_url, {action: 'getloginmember'}, function (data) {
            data = JSON.parse(data);

            if (data['id'] > 0) {
                cb(data);
            } else {
                cb(0);
            }
    });
}

Then

get_login_member($, function(row) {
    // put your code here
}); 

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