[英]Alternative for ajax async: false
在ajax完成之前中断属性火灾。 我发现的唯一解决方案是使“异步:假”。 但已弃用。 有没有更好的选择来等待ajax完成而不将async设置为false?
$.getJSON(jsonUrl, function(data) {
var type, json, options;
var globalData = data;
$.each(globalData.properties, function(key, value) {
switch(value.type) {
case 'string':
type = '<input type="text">'
break;
case 'int':
type = '<input type="number" min="0">'
break;
case 'decimal':
type = '<input type="number" min="0" step="0.01">'
break;
case 'date':
type = '<input type="date">'
break;
case 'boolean':
type = '<input type="checkbox">'
break;
case 'json':
json = './assets/json/' + value.json_name + '.json'
$.ajax({
async: false,
url: json,
success: function(data) {
$.each(data, function(index, item) {
options += '<option value=' + item.key + '>' + item.value + '</option>'
})
type = '<select id="issue-form"><option disabled selected value></option>' + options + '</select>';
}
});
break;
}
listItem += '<li class="questionnaire_item">' +
'<label>' +
'<div class="question">' +
value.description + ':' +
'</div>' +
'<div class="input">' +
type +
'</div>' +
'</label>' +
'</li>';
type = '';
})
form.innerHTML += listItem;
$('.content').append(form)});
解决此问题的最佳方法是将中断或操作放在ajax请求的成功回调中,此外,您可以在ajax请求的beforeSend
回调中使用布尔值集,然后等待布尔值仍然为false :
$.getJSON(jsonUrl, function(data) {
var type, json, options;
var globalData = data;
$.each(globalData.properties, function(key, value) {
var isBusy = false;
switch(value.type) {
case 'string':
type = '<input type="text">'
break;
case 'int':
type = '<input type="number" min="0">'
break;
case 'decimal':
type = '<input type="number" min="0" step="0.01">'
break;
case 'date':
type = '<input type="date">'
break;
case 'boolean':
type = '<input type="checkbox">'
break;
case 'json':
json = './assets/json/' + value.json_name + '.json'
$.ajax({
async: false,
url: json,
beforeSend: function(){
isBusy = true;
},
success: function(data) {
isBusy = false;
$.each(data, function(index, item) {
options += '<option value=' + item.key + '>' + item.value + '</option>'
})
type = '<select id="issue-form"><option disabled selected value></option>' + options + '</select>';
}
});
while(isBusy) {}
break;
}
listItem += '<li class="questionnaire_item">' +
'<label>' +
'<div class="question">' +
value.description + ':' +
'</div>' +
'<div class="input">' +
type +
'</div>' +
'</label>' +
'</li>';
type = '';
})
form.innerHTML += listItem;
$('.content').append(form)});
但是,这再次打破了提出AJAX请求的要点,您最好在加载页面之前先准备数据,然后再显示它。
老实说,这种解决方案不是最好的解决方案,正如罗里在评论中所说,我会承诺。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.