简体   繁体   中英

jQuery Ajax Post - Unable to set global variable using callback function?

I have the following ajax method. On success I want to set a global variable but it doesn't seem to work - console returns empty object. It only works if I define async to false. However I'd like to keep the ajax method asynchronous. How can I get this to work?

var appointment = {};

if ($("#Appointment").is(":checked")) {
     $.ajax({
            type: "POST",
            url: "someurl",
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify({
                dateStart: moment()
            }),
           // async: false,
            dataType: "json",
            success: function(data) {
                ajaxCallBack(data);
            }
    });

    function ajaxCallBack(data) {
            var response = $.parseJSON(data.d);
            appointment = { startDate: response.startDate, endDate: response.endDate };
    }
}

console.log(appointment);

console.log() is triggered before ajaxCallback() and before appointment is set ( ajax is asynchronous), to show appointment in console you can run:

function ajaxCallBack(data) {
        var response = $.parseJSON(data.d);
        appointment = { startDate: response.startDate, endDate: response.endDate };
        console.log(appointment);
}

or

function ajaxCallBack(data) {
        var response = $.parseJSON(data.d);
        appointment = { startDate: response.startDate, endDate: response.endDate };
        printAppointment();
}

// define as global:
function printAppointment() {
    console.log(appointment)
}

Ajax happens asynchronously, meaning code that appears after it won't wait for it to complete. So your console.log is executing before the ajax has necessarily gotten what it needs to populate the object.

Try moving your console.log statement inside of the callback - put it right after the line where you set appointment .

ajax is an asynchronous operation. So console.log will execute even before ajax success . console the variable from ajaxCallBack function

function ajaxCallBack(data) {
  var response = $.parseJSON(data.d);
  appointment = { startDate: response.startDate,
                  endDate: response.endDate };
  console.log(appointment);
}

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