开发者

Textbox Onchange Get Result Count

开发者 https://www.devze.com 2023-04-11 00:55 出处:网络
I have a text box for searching my photos website. As a user types, instead of showing a list of suggestions, I would开发者_如何学Python like to show a count of results, informing my user that there a

I have a text box for searching my photos website. As a user types, instead of showing a list of suggestions, I would开发者_如何学Python like to show a count of results, informing my user that there are photos for what they are typing.

I will add an 'onChange' event to my text box, that will call my AJAX function. The function will then gather what has been typed already, AJAX it to my ASP page that produces the count and posts it back to display.

I know how to accomplish this but I don't know how it will work on performance. The problem I foresee is if the user types a really long string, really quickly, it might have to do 50 calls (for each character in string). The ASP/SQL search query, that produces the count, is also very large, and can take between 0.8 - 1.0 seconds to produce a count.

Is this going to cause me problems? How will this actually work? If the user is typing character 42, will the AJAX still be processing character 12, trying to catch up with the user? Will it jam? If another call is made does it cancel the old one if it hasn't got a response?

Any suggestions/experiences gratefully received.


The solution that I typically provide for my own applications is to ONLY initiate an ajax request after the user has stopped typing for a certain period of time (say, 0.75 seconds). For every keystroke, [re]start a javascript timeout (setTimeout) for some time (perhaps 0.75 seconds). Each keystroke that a user generates cancels this timeout and restarts it. This way the ajax will only happen after the user hasn't typed anything for that period of time (0.75 seconds). Here is some code to demonstrate.

var __global_timeout = null;
function getResultCountWrapper () {
    if (__global_timeout)
        clearTimeout(__global_timeout);
    __global_timeout = setTimeout(getResultCount, 0750);
}

function getResultCount () {
    // ajax call goes here.
}

This is what you would place on your text input box.

<input type="text" onchange="getResultCountWrapper()";>

Here is a complete web page that works as advertised:

<html>
  <head>
    <script type="text/javascript">
      var __global_timeout = null;
      function getResultCountWrapper () {
        if (__global_timeout)
          clearTimeout(__global_timeout);
        __global_timeout = setTimeout(getResultCount, 0750);
      }

      function getResultCount () {
        // ajax call goes here.
        alert('wee');
      }

    </script>
  </head>
  <body>
    <input type="text" onchange="getResultCountWrapper()";>
  </body>
</html>
0

精彩评论

暂无评论...
验证码 换一张
取 消