[英]js stop click function subsequent execution after call back in ajax of itself
[英]Stop JS function execution while an AJAX call is not finished
我编写了一个小功能来动态包含CSS文件或JS文件。 我使用jquery函数$.getScript()
加载JS文件。
我想防止我的AJAX调用完成之前函数返回。
我已经尝试过类似的方法,但是不起作用:
CAPTIVEA.resources._includeResource = function(resource) {
var ret = false;
if (CAPTIVEA.resources.isIncluded(resource))
{ // Resource already included => do nothing
console.log('CAPTIVEA.resources : "' + resource + '" is already included.');
ret = true;
}
else
{ // Resource not included => try to include it
var resType = CAPTIVEA.resources.getType(resource);
switch (resType)
{ // Check resource type to know how to include it
case 'js':
$.when(
$.getScript(resource, function(data, textStatus){
console.info('CAPTIVEA.resources : "' + resource + '" dynamically loaded.'); //success
})
).done(function(){
ret = true;
});
break;
case 'css':
// Load CSS file ...
break;
default:
console.error('CAPTIVEA.resources : "' + resource + '" is not an includable resource.');
break;
}
}
return ret;
}
您可以使用$ .ajax并将async设置为false,以使其在继续之前等待响应:
$.ajax({
url: resource,
success: function(data, textStatus) {
console.info('CAPTIVEA.resources : "' + resource + '" dynamically loaded.'); //success
},
dataType: 'script',
async: false
});
使用此功能通常不需要同步调用。 AJAX的全部要点是它是异步的。 第一个A代表异步 。
为什么需要阻止函数返回? 通常是因为要在加载资源时使用资源(在本例中为脚本)。 您必须改用回调:
错误:
$.getScript(resource);
doSomethingWithResource();
对:
$.getScript(resource, function() {
doSomethingWithResource();
});
尝试这个:
CAPTIVEA.resources._includeResource = function(resource) {
var ret = false;
if (CAPTIVEA.resources.isIncluded(resource))
{ // Resource already included => do nothing
console.log('CAPTIVEA.resources : "' + resource + '" is already included.');
ret = true;
}
else
{ // Resource not included => try to include it
var resType = CAPTIVEA.resources.getType(resource);
successFlag = false;
switch (resType)
{ // Check resource type to know how to include it
case 'js':
jQuery.ajax({
async:false,
type:'POST',
url: resource,
data: null,
success: function(){successFlag =true;}
});
break;
case 'css':
// Load CSS file ...
break;
default:
console.error('CAPTIVEA.resources : "' + resource + '" is not an includable resource.');
break;
}
ret = successFlag;
}
return ret;
}
我认为它是唯一的解决方案,即使我们必须添加一个全局变量(successFlag)。 另一种解决方案是在成功回调中执行您必须做的事情,但是那样您的功能将无法按预期工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.