2014-03-06 25 views
0

我試過在互聯網上搜索,發現沒有簡單的答案,我相信存在兩個我遇到的問題。我的jquery UI自動完成功能如下:當輸入空格時取消自動填充請求,並且僅在用戶停止輸入時才觸發。

$('#moviename').autocomplete({ 
      // URL is parsed by my framework 
      source:"<?=URL::route('MovieAutocomplete')?>", 
      minLength:2, 
      dataType:"json", 
      select:function(event,ui){ 
       // set artist id 
       $('#movieid').val(ui.item.id); 
       $('#moviename').prop('disabled',true); 
       $('#moviedetails').prop('disabled',false); 
       $('#movieclear').html('Clear'); 
       $('#moviehint').toggle(); 
      } 
}); 

此代碼有效。不過,我正在看錶現。我有兩個問題:

  1. 我的控制器在看到空白項時取消請求。但是,我希望在請求發送之前檢查這個條件。我已經和beforeSend一起玩過了,但是它不起作用。有人能幫我完成這個嗎?

  2. 我還想僅在用戶停止輸入時觸發AJAX請求,比如說給它一個500ms的時間來等待它發送請求到服務器。有沒有簡單的方法來做到這一點?我猜「call autocomplete inside a keyup event which will be bound to the field I want」。請幫幫我。

如果有人能爲我看這個,那將會很棒。

+0

您的beforesend代碼是什麼樣的? – canoe

+0

謝謝,它的功能(){var 0 = $ .trim() if(a.length <1)return false; 返回true; }' –

回答

1

我最近一直在使用jQuery UI autocomplete。這是我使用的邏輯&它運作良好。

onKeydownMethod: function(event) { 
     if ($(this).val().length >= App.autocompleteMinLength) 
     { 
if ($(this).val().length >= YOUR_MIN_LENGTH) {   
$('selector').autocomplete({ 
    minLength: YOUR_MIN_LENGTH, // min number of chars before request is made. 
    delay: YOUR_DELAY, // mum of miliseconds to wait before making request. 
    source: function(request, callback) { 
     $.ajax({ 
      type: 'get', 
      contentType: 'application/json', 
      url: 'YOUR_URL' + ANY_PARAMS, 
      dataType: 'json', 
      timeout: 50000 
     }).done(function(response) { 
      callback(response); // I used a callback to send data back to the parent function. Handle the response however you like here. 
     }).fail(function(error) { 
      switch (error.statusText) 
      { 
       case 'OK': 
        // handle response. 
       break; 
       default: 
        // handle response 
       break; 
      } 
     }); 
    } 
}); 
} 
} 
+0

這回答了我的第二個問題,謝謝。然而,我怎樣才能解決第一個問題呢?在請求發送之前,我沒有看到任何需要檢查的條件 –

+0

只是一個想法,但是您可以在那裏調用一個函數來檢查它嗎?如果它是好的 - 返回一個整數?因爲「minLength」正在尋找一個整數。 或者,在您的鍵盤處理程序上,您可以檢查字符串的實際長度 - 然後執行自動填充。因爲您已經驗證了(或多或少),所以只需在該點使用0作爲最小長度。 類似於: if($(this).val()。length> = YOUR_MINLENGTH){// init autocomplete。 } – Damon

+0

編輯:我更新了上面的示例代碼,以幫助給出我在說什麼的想法。希望能幫助到你! – Damon

相關問題