我有一个页面,用户可以点击一个按钮来通过xhr获取请求检索数据。在数据加载和解析时,我想要显示一个加载消息,一旦准备就绪,数据将被替换为数据。我使用的是dojo库,所以不用包含jQuery或其他库。如何强制javascript执行顺序
这是建立我使用的简化版本:
HTML
<div id = "clickMe"> Click Me! </div>
<div id = "results" class = "hidden">
Please wait while we retrieve the results
</div>
CSS
.hidden {display: none;}
的Javascript
// Bind function to click me div
var clickMe = document.getElementById('clickMe');
clickMe.addEventListener('click', getResults, false);
function getResults() {
// Display the loading message while results are retrieved
var resultsDiv = document.getElementById('results');
resultsDiv.classList.remove('hidden');
// Get the data and parse it here using a standard dojo.xhrGet method
var displayResults = getData();
// Output data to resultsDiv, overwriting loading message
resultsDiv.innerHTML = displayResults;
}
我的问题m有就是getRes ults函数总是等到getData函数完成后才移除'hidden'类并显示结果div。这意味着即使处理数据时有延迟,用户也不会看到加载消息,只能看到检索到的数据。但是,如果我把中间的功能被强制暂停警报,显示加载消息:
function getResults() {
// Display the loading message while results are retrieved
var resultsDiv = document.getElementById('results');
resultsDiv.classList.remove('hidden');
// The loading message will be displayed if this alert is included
alert ("Hello world!");
// Get the data and parse it here using a standard dojo.xhrGet method
var displayResults = getData();
// Output data to resultsDiv, overwriting loading message
resultsDiv.innerHTML = displayResults;
}
我试图用的console.log更换警报,但恢复到不显示加载消息。我也尝试设置获取数据作为显示加载消息内的回调函数,但它又不显示任何内容。我也尝试将get请求设置为sync:true以及sync:false,但同样没有运气。
如何确保在等待getData时显示加载消息?
编辑:
这是getData函数。我尝试了同步和不同步。
function getData() {
var targetUrl = //some url;
var restResponse;
dojo.xhrGet({
url: targetUrl,
sync: true; // no difference when this is omitted
load: function(result) {
restResponse = result;
}
});
// Parse the rest response - fairly long function so I won't paste it here
var parsedResponse = parseResult(restResponse);
return parsedResponse;
}
删除'='从CSS :-) – Bergi
复制的[如何返回从AJAX调用的响应?](http://stackoverflow.com/questions/14220321/how-to-return - 回应从一个阿贾克斯调用) – Bergi
@ Bergi - 道歉,我写这个很快,而不是复制和粘贴。该=没有在我的原始代码:)已编辑相应。 – Emma