简体   繁体   English

如何减少XMLHttpRequest的时间滞后?

[英]How to reduce XMLHttpRequest time lag?

I use a XMLHttpRequest on a signup form to see if the username they entered has been taken already. 我在注册表单上使用XMLHttpRequest来查看他们输入的用户名是否已被使用。 The script runs fine, but I notice that there's some time delay when making the request - the webpage is frozen for a second, after sending the request. 该脚本可以正常运行,但是我注意到发出请求时会有一些时间延迟-发送请求后,该网页被冻结了一秒钟。

Is there a way to have the request "in the background" and not cause any lag on the front end? 有没有办法让请求“在后台”并且不会在前端造成任何滞后? I like Twitter's implementation: it shows an spinning hourglass icon while it's searching the database. 我喜欢Twitter的实现:它在搜索数据库时显示一个旋转的沙漏图标。 How do I get something similar? 我如何得到类似的东西?

You want to use asynchronous XHR -- currently you're performing a synchronous request, so the page has to freeze until the load has complete. 您要使用异步XHR-当前正在执行同步请求,因此页面必须冻结,直到加载完成。 Asynchronous XHR calls a callbck function you provide with the load status updates. 异步XHR调用随负载状态更新一起提供的callbck函数。

If memory serves you just need to do 如果有记忆,您只需要做

 xhr.onreadystatechange = function() { 
     if (xhr.readyState === 4 && xhr.status === 200) loadFinished();
 }
 xhr.open(requestType, url,  true);

Where true makes the request asynchronous. 如果为true使请求异步。

You need to specify that XMLHttpRequest operate asynchronously--in the background. 您需要指定XMLHttpRequest在后台异步运行。 Then you can provide a callback function so users can continue browsing until the operation is complete. 然后,您可以提供回调函数,以便用户可以继续浏览直到操作完成。

Many sites simply show an animated GIF while waiting for the operation to return, which probably gives the user the impression that you're looking for since it looks like something is happening. 许多站点在等待操作返回时仅显示动画GIF,这可能会给用户留下您正在寻找的印象,因为它看起来正在发生某些事情。 You can design and download one of those AJAX-spinning indicators easily at http://www.ajaxload.info/ . 您可以从http://www.ajaxload.info/轻松设计和下载这些AJAX旋转指示器之一。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM