如何在浏览器中同步ajax调用期间显示等待消息
如何在浏览器中同步ajax调用时显示等待消息? 我尝试了下面的代码,关闭了网络服务器,但没有显示“正在保存”消息。
一段时间后,只发生来自 ajax 调用的错误事件,没有任何进度消息。
如果同步 ajax 调用正在进行中,如何向用户显示等待消息?
var myInfo = '<div class="ui-state-highlight ui-corner-all" style="position: fixed;' +
'z-index: 10000; margin-top: 2%; margin-left: 2%">' +
' <br />' +
' <span class="ui-icon ui-icon-info" style="float: left; margin-right: .3em;"></span>' +
'<strong>Saving</strong> <br />' +
'<br /></div>'
$('#_info').html(myInfo);
$('#_info').show();
$.ajax( 'save',
{
async: false,
type: 'POST'
} );
How to show waiting message on sync ajax call in browser ?
I tried code below, turned web server off but "Saving" message is not displayed.
After some time only error event from ajax call occurs, without any progress message.
How to show waiting message to user if sync ajax call is in progress ?
var myInfo = '<div class="ui-state-highlight ui-corner-all" style="position: fixed;' +
'z-index: 10000; margin-top: 2%; margin-left: 2%">' +
' <br />' +
' <span class="ui-icon ui-icon-info" style="float: left; margin-right: .3em;"></span>' +
'<strong>Saving</strong> <br />' +
'<br /></div>'
$('#_info').html(myInfo);
$('#_info').show();
$.ajax( 'save',
{
async: false,
type: 'POST'
} );
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的问题是您正在使用同步 AJAX 调用,并且几乎会锁定浏览器直到它完成。特别是,在您点击
$.ajax({async:false})
锁定之前,浏览器将无法显示“正在加载”消息;例如,观察它的作用:请注意,该按钮甚至没有变回未单击的视觉状态当 AJAX 运行时?
解决方案是显示您的加载消息,将控制权交还给浏览器,然后通过同步远程调用锁定所有内容。一种方法是使用延迟为零的
setTimeout
:例如: http://jsfiddle.net/ambigously/zLnED/
当然需要一些小心,因为
this 内部不会相同
setTimeout
回调,因为它在外部,但很容易处理。不过,使用
async:false
对用户来说并不是一件好事,除非绝对必要(而且很少有必要),否则您应该尽量避免使用它。Your problem is that you're using a synchronous AJAX call and that pretty much locks up the browser until it completes. In particular, the browser won't be able to show your "loading" message before you hit the
$.ajax({async:false})
lockup; for example, watch what this does:Notice that the button doesn't even change back to the unclicked visual state while the AJAX is running?
The solution is to show your loading message, hand control back to the browser, and then lock everything up with your synchronous remote call. One way to do this is to use
setTimeout
with a delay of zero:For example: http://jsfiddle.net/ambiguous/zLnED/
Some care will be needed of course as
this
won't be the same inside thesetTimeout
callback as it was outside but that's easy to take care of.Using
async:false
isn't a very nice thing to be doing to your users though, you should try to avoid it unless it is absolutely necessary (and it rarely is).正在加载...
您的ajax调用:
<div class="loading">Loading...</div>
Your ajax call: