1

I use a XMLHttpRequest on a signup form to see if the username they entered has been taken already. 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. How do I get something similar?

4

2 回答 2

7

You want to use asynchronous XHR -- currently you're performing a synchronous request, so the page has to freeze until the load has complete. Asynchronous XHR calls a callbck function you provide with the load status updates.

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.

于 2009-05-29T01:29:49.543 回答
1

You need to specify that XMLHttpRequest operate asynchronously--in the background. 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. You can design and download one of those AJAX-spinning indicators easily at http://www.ajaxload.info/.

于 2009-05-29T01:31:32.723 回答