2011-08-09 173 views
1

像這樣的jquery代碼,我應該如何延遲ajax請求?輸入是一個文本字段...在我的頭.... thx求助...我應該如何延遲ajax請求?

var proname = "" ; 
$("input[name='proname']").keyup(function(e){ 
    //how should i delay this function on here ? 
    if (e.which == 13) return ; 
    if ($(this).val() != proname) 
    { 
     proname = $(this).val() ; 
    } 
    else 
    { 
    return ; 
    } 
    $.ajax({ 
     type: "post", 
     data: "proname="+proname+"&page=1", 
     url: "/project/searchrate", 
     success: function(view){ 
      alert(view) ; 
     } 
    }) ; 
}) ; 
+1

https://developer.mozilla.org/en/window.setTimeout – Phil

回答

0

使用setTimeout

var proname = "" ; 
$("input[name='proname']").keyup(function(e){ 
    if (e.which == 13) return; 
    setTimeout(function() { 
     if ($(this).val() != proname) { 
      proname = $(this).val(); 
     } else { 
      return; 
     } 
     $.ajax({ 
      type: "post", 
      data: "proname="+proname+"&page=1", 
      url: "/project/searchrate", 
      success: function(view){ 
       alert(view) ; 
      } 
     }); 
    }, DELAY_IN_MSECS); 
}); 
3

您想使用setTimeout

從您的使用情況來看,每次發生另一個keyup事件時都會清除一個超時值以避免隊列,這似乎是個好主意。

var requestDelay; 
var proname; 

$('input[name=proname]').keyup(function() { 

    if(e.which == 13 || $(this).val() == proname) 
     return; 

    proname = $(this).val(); 

    // postpone the submit another 300 ms upon every new character 
    window.clearTimeout(requestDelay); 

    requestDelay = window.setTimeout(function() { 
     $.ajax(...); 
    }, 300); 


}); 
0
$("input[name='proname']").keyup(function(e){ 
     //how should i delay this function on here ? 
     if (e.which == 13) return ; 
    setTimeout(function() { 
     if ($(this).val() != proname) 
     { 
      proname = $(this).val() ; 
     } 
     else 
     { 
     return ; 
     } 
     $.ajax({ 
      type: "post", 
      data: "proname="+proname+"&page=1", 
      url: "/project/searchrate", 
      success: function(view){ 
       alert(view) ; 
      } 
     }) ; 

     }, 1000);  
}) ;