在我的应用程序中,我使用Ext.Ajax.request
来加载脚本,并使用eval
执行它们。
问题是由于 AJAX 请求需要时间才能完成,在 AJAX 加载的脚本中定义的变量需要在之后执行的代码中使用。在这个例子中,我展示了这种情况。如何更改此代码,使得在 AJAX 请求加载并执行脚本之后才执行 JavaScript 代码?
testEvalIssue_script.htm:
<script type="text/javascript">
console.log('2. inside the ajax-loaded script');
</script>
main.htm:
<html>
<head>
<script type="text/javascript" src="ext/adapter/ext/ext-base.js"></script>
<script type="text/javascript" src="ext/ext-all-debug.js"></script>
<script type="text/javascript">
function loadViewViaAjax(url) {
Ext.Ajax.request({
url: url,
success: function(objServerResponse) {
var responseText = objServerResponse.responseText;
var scripts, scriptsFinder=/<script[^>]*>([\s\S]+)<\/script>/gi;
while(scripts=scriptsFinder.exec(responseText)) {
eval.call(window,scripts[1]);
}
}
});
}
console.log('1. before loading ajax script');
loadViewViaAjax('testEvalIssue_script.htm');
console.log('3. after loading ajax script');
</script>
</head>
<body>
</body>
</html>
输出:
1. before loading ajax script
3. after loading ajax script
2. inside the ajax-loaded script
我该如何使输出按照正确的顺序呈现,就像这样:
1. before loading ajax script
2. inside the ajax-loaded script
3. after loading ajax script