运行我的JavaScript时,它将调用getDoctorComplete
函数。 AJAX请求完成后,它将设置a = chelsea
。否则,将进行触发器更改并运行$('#dropdown_hosp').change(...
。在$('#dropdown_hosp').change(...
中,它将调用getSpecialty
函数。使用getSpecialty
函数完成AJAX请求后,我想获取a
的值。我console.log
,但其中包含一个空字符串。我该如何解决这个问题?
var a = '';
$(document).ready(function () {
app.getHospital({
areaId: ''
});
app.getDoctorComplete({
doctorId: doctorId,
doctorel: $('#dropdown_doct')
});
$('#dropdown_hosp').change(function () {
var dropdownspecialty = $('#dropdown_spec');
app.getSpecialty({
hospitalId: $('#dropdown_hosp').val(),
apiUrl: 'api',
special: dropdownSpec
});
});
});
app = function () {
function getHospital({
areaId
}) {
// ...
$.ajax({
// ...
success: function (result) {
// ...
},
// ...
}).done(function () {
$('#dropdown_hosp').select2();
});
};
function getSpecialty({
hospitalId,
apiUrl,
special
}) {
// ...
$.ajax({
// ...
}).done(function () {
// test here
console.log(a);
});
};
function getDoctorComplete({
schdoctor_id,
doctorel
}) {
// ...
$.ajax({
// ...
success: function (result) {
// ...
},
// ...
}).done(function () {
// ...
a = 'chelsea';
b = '..';
$('#dropdown_hosp').val(b).trigger('change');
});
};
return {
getSpecialty: getSpecialty,
getDoctorComplete: getDoctorComplete
}
}();
答案 0 :(得分:1)
您的问题在于,您的ajax
呼叫是异步的,因此a
在登录时不会重新分配。这将是使用Promise
,创建异步函数resolve
,标记该异步函数的return
和.then()
之后执行某些操作的解决方案异步功能:
var a = '';
$(document).ready(function () {
app.getHospital({
areaId: ''
});
app.getDoctorComplete({
doctorId: doctorId,
doctorel: $('#dropdown_doct')
})
.then(() => { // Add the .then() callback to do something after getDoctorComplete finished
$('#dropdown_hosp').change(function () {
var dropdownspecialty = $('#dropdown_spec');
app.getSpecialty({
hospitalId: $('#dropdown_hosp').val(),
apiUrl: 'api',
special: dropdownSpec
});
});
});
});
app = function () {
function getHospital({
areaId
}) {
return new Promise((resolve, reject) => {
// ...
$.ajax({
// ...
success: function (result) {
// ...
},
// ...
}).done(function () {
$('#dropdown_hosp').select2();
resolve(); // Add resolve
});
});
};
function getSpecialty({
hospitalId,
apiUrl,
special
}) {
return new Promise((resolve, reject) => {
// ...
$.ajax({
// ...
}).done(function () {
// test here
console.log(a);
resolve(); // Add resolve
});
});
};
function getDoctorComplete({
schdoctor_id,
doctorel
}) {
return new Promise((resolve, reject) => {
// ...
$.ajax({
// ...
success: function (result) {
// ...
},
// ...
}).done(function () {
// ...
a = 'chelsea';
b = '..';
$('#dropdown_hosp').val(b).trigger('change');
resolve(); // Add resolve
});
});
};
return {
getSpecialty: getSpecialty,
getDoctorComplete: getDoctorComplete
}
}();