开发者

jQuery keyUp/AJAX get combo always 1 or 2 strokes behind

开发者 https://www.devze.com 2023-01-16 23:01 出处:网络
I built a very simple Twitter Instant Search for fun, using jQuery and PHP. I bind an event to keyup on the search form, and make a quick AJAX call to a PHP page that curls Twitter Search JSON.

I built a very simple Twitter Instant Search for fun, using jQuery and PHP. I bind an event to keyup on the search form, and make a quick AJAX call to a PHP page that curls Twitter Search JSON.

<script>
$(function(){
 $('#search').bind('keyup', function(){
  var v = $('#search').val();
  console.log(v);
  $.get('get.php',{q: v, a:''}, function(data){
   obj开发者_开发问答 = {};
   window.tw = '';
    obj = eval('('+ data +')');
  if(typeof obj.results.length !== undefined){
    for (var i=0; i < obj.results.length; i++) {
     tw += '<div class="tweet"><h2><a target="_blank" href="http://twitter.com/'+obj.results[i].from_user+'">@'  + obj.results[i].from_user + '</a></h2> <span>' + obj.results[i].text + '</span><' + '/div>';
    };
    }
   });
 $('#container').html(window.tw);  
 });

});
</script> 

Even though the console.log value returned is right, it still falls behind 1-2 characters, in terms of the results it displays. Why? How can I fix this?


$('#container').html(window.tw); 

This should be inside the callback given to $.get()

$(function(){
    $('#search').bind('keyup', function(){
        var v = $('#search').val();
        console.log(v);
        $.get('get.php',{q: v, a:''}, function(data){
            obj = {};
            window.tw = '';
                        obj = eval('('+ data +')');
                        if(typeof obj.results.length !== undefined){
                for (var i=0; i < obj.results.length; i++) {
                    tw += '<div class="tweet"><h2><a target="_blank" href="http://twitter.com/'+obj.results[i].from_user+'">@'  + obj.results[i].from_user + '</a></h2> <span>' + obj.results[i].text + '</span><' + '/div>';
                };
            }
            $('#container').html(window.tw);    
        });

    });
});


Seems like you're sending out the AJAX request immediately. Once you do that, the code becomes asynchronous, meaning it can come back in any order depending on latency. If the results return the original search term, you could perform a match on to make sure the returned results still match what's in the search box.


Are you sure the problem isn't in the get.php part of the process?

edit

Ah, I think I spotted the problem. I think the call to

 $('#container').html(window.tw); 

Needs to be in the $.get success callback, not in the keyup event function - as it is, that fires before the $.get has returned anything so it's showing the last set of responses instead. A single letter search doesn't return any results.

0

精彩评论

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