Ajax 非同期リクエストによって入力された複数の HTML リストがあります。これらのすべての要求が終了したら (多数の要求があります)、顧客レコードに対応するリスト項目を選択してフォームに入力する必要があります。
これを達成するために deferreds を使用しようとしていますが、リストが作成されるずっと前に関数が起動してしまいます。何か案は?
$.when(
$.ajax({
url: "get-status.php",
async: true,
dataType: 'json',
success: function (j) {
var options = '';
$.each(j, function(key, value) {
options += '<option value="' + key + '">' + value + '</option>';
});
$("select#status_id").html(options);
}
}),
$.ajax({
url: "get-groups.php",
async: true,
dataType: 'json',
success: function (j) {
var options = '';
$.each(j, function(key, value) {
options += '<option value="' + key + '">' + value + '</option>';
});
$("select#group_id").html(options);
}
})
).then(populateForm('form1',customer_id));
実際のアプリケーション コード:
<!-- Main function -->
populateFormBoxSS = function(id){
$.ajax({
url: "get-json-fich_ss.php?id="+id,
async: false,
dataType: 'json',
success: function (j) {
// Populate drop-downs
$.when(populateEstadosTest('box-estado_id')).then(populateFormGeneric(j, "box"));
}
});
}
<!-- Generic Form Population -->
populateFormGeneric = function (j, target) {
$.each(j, function(key, value) {
switch ($('#'+target+'-'+key).attr('type')) {
case 'checkbox':
if(value==1) {
$('#'+target+'-'+key).attr('checked', true);
}
break;
default:
$('#'+target+'-'+key).val(value);
break;
}
});
return function(){
// Do nothing
}
}
<!-- Dropdown list population -->
populateEstadosTest = function(field){
var dfd = new $.Deferred();
$.ajax({
url: "get-json-esta.php",
async: true,
dataType: 'json',
success: function (j) {
var options = '';
$.each(j, function(key, value) {
options += '<option value="' + key + '">' + value + '</option>';
});
$("select#"+field).html(options);
// Resolve Deferred
dfd.resolve();
}
});
return dfd.promise(); // Returns a promise
}