javascript 在 AJAX 调用之前加载预加载器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8432178/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Load preloader before AJAX call
提问by KeatsKelleher
I have an AJAX call I'm making. It's synchronous so it 'hangs' while the content loads. Before the AJAX call I append a preloading image to the soon-to-be parent node of the incoming content:
我有一个 AJAX 调用。它是同步的,所以它在内容加载时“挂起”。在 AJAX 调用之前,我将预加载图像附加到即将成为传入内容的父节点:
function makePreLoader( parentNode )
{
var img = document.createElement( "img" );
img.src = "images/preloader.gif";
parentNode.appendChild( img );
}
function getData( )
{
var parentNode = document.getElementById( "myParentNode" );
makePreloader( parentNode );
$.ajax(
"http://www.example.com/",
{
success: function( resp )
{
$( parentNode ).html( resp );
},
async: false
}
);
}
My script at example.com is a simple php script that hangs 7 seconds and then replies "done".
我在 example.com 上的脚本是一个简单的 php 脚本,它会挂起 7 秒然后回复“完成”。
When I call 'getData' the expected behavior is to see the preloading image load, and then it should be replaced by "done".
当我调用“getData”时,预期的行为是查看预加载图像加载,然后应将其替换为“完成”。
The actual behavior is the call hangs (apparently without appending the preloader) and then loads the content.
实际行为是调用挂起(显然没有附加预加载器)然后加载内容。
Has anyone had a similar issue? Can someone recommend a good solution?
有没有人有类似的问题?有人可以推荐一个好的解决方案吗?
回答by Rafay
use ajaxStart
instead
使用ajaxStart
替代
here is an example how to do it
这是一个如何做到的例子
回答by Rakesh Pai
There isn't a good solution, except to make the call asynchronous. A synchronous Ajax call, by definition, blocks the UI thread. Hence all operations on the UI gets suspended till the call responds. Thats why it seems like the UI is hung.
除了使调用异步之外,没有好的解决方案。根据定义,同步 Ajax 调用会阻塞 UI 线程。因此,UI 上的所有操作都会暂停,直到呼叫响应。这就是为什么 UI 似乎被挂起的原因。
tl;dr: Use asynchronous ajax. There are few, if any, good reasons you should do sync calls.
tl;dr:使用异步 ajax。您应该进行同步呼叫的理由很少(如果有的话)。