JavaScript 加载图像在进行 ajax 调用时冻结
我使用 jQuery 构建了一个页面,该页面使用异步 Ajax 调用。我试图显示一个正在加载的 gif,但我怎么也无法让它工作。 gif 永远不会显示。有什么想法吗?
function updateCityList(state) {
$("#city-loading").empty().html('<img src="/Images/loading.gif" />');
$.ajax(
{
type: "GET",
async: true,
url: "/NPA/GetCities/" + state,
dataType: "json",
success: function(optionData) {
var options = [];
$(optionData).each(function(index, optionData) {
if ($('#cities option[value=' + optionData.Value + ']').length == 0)
options.push(optionData);
});
$("#cityList").fillSelect(options);
}
});
$("#city-loading").empty();
};
I've built a page using jQuery that uses an async Ajax call. I'm trying to display a loading gif but for the life of me I can't get it to work. The gif never displays. Any ideas?
function updateCityList(state) {
$("#city-loading").empty().html('<img src="/Images/loading.gif" />');
$.ajax(
{
type: "GET",
async: true,
url: "/NPA/GetCities/" + state,
dataType: "json",
success: function(optionData) {
var options = [];
$(optionData).each(function(index, optionData) {
if ($('#cities option[value=' + optionData.Value + ']').length == 0)
options.push(optionData);
});
$("#cityList").fillSelect(options);
}
});
$("#city-loading").empty();
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您对
$.ajax()
的调用会引发请求,然后立即继续,因为您正在异步执行调用。因此,对$("#city-loading").empty();
的调用会立即发生。您需要将
$("#city-loading").empty();
移动到success:
函数的末尾,这样就不会被调用直到 AJAX 请求完成。Your call to
$.ajax()
sets off the request and then immediately continues, because you're doing the call asynchronously. Hence the call to$("#city-loading").empty();
happens immediately.You need to move the
$("#city-loading").empty();
to the end of thesuccess:
function, so that it doesn't get called until the AJAX request completes.首先你调用:
然后是ajax调用,因为它是异步代码执行将继续并执行这个:
你应该在ajax回调中隐藏图像:
first you call:
then is the ajax call, since it is async code execution would continue and execute this:
You should hide the image in ajax callback:
我将提供无代码的解释。您正在动态地将 HTML 添加到 DOM(img src)。 DOM 具有独立于 Javascript 执行的自然延迟。这意味着首先进行 ajax 调用,然后应用程序从服务器下载图像。
最好的解决方案是将图像添加到页面。确认图像已加载到 DOM 中。 (为图像对象添加一个id,然后使用查询来确认您可以访问它)。然后进行 ajax 调用。
另一种选择可能是预加载图像,这样就不需要服务器下载。
I'll provide a code-free explanation. You are adding HTML to the DOM dynamically (the img src). The DOM has a natural latency that is independent of the Javascript execution. What this means is that your ajax call is made first, then the application downloads the image from the server.
Your best solution is to add the image to the page. Confirm that the image is loaded into the DOM. (add an id to the image object, and then use a query to confirm that you can access it). Then make your ajax call.
Another option might be to pre-load the image so there's no server download required.