2012-01-27 82 views
4

我正在使用Jquery自動完成。如果用戶鍵入2個字符,然後等待,然後鍵入另一個。如果第一個響應在第二個響應之後出現,它將簡要顯示第二個清單,然後顯示第一個清單。如何在用戶開始輸入更多內容後取消第一個請求?jquery UI自動完成顯示早期文本的響應

$("#city").autocomplete({ 
     source: function(request, response) { 
      $.ajax({ 
       url: "/geo/json_autocomplete.php", 
       dataType: "json", 
       data: { 
        term: $("#city").val(), 
        countryid: $("#countryid").val() 
       }, 
       success: function(data) { 
        response($.map(data, function(item) { 
         //console.debug(item.value+" "+item.label+" "+item.id); 
         return { 
          label: item.label, 
          value: item.value, 
          id: item.id 
         } 
        })); 
       } 
      }); 
     }, 
     minLength: 2, 
     delay: 500, 
     select: function(event, ui) { 
      $("#cityid").val(ui.item.id); 
      showForm(); 
     } 
    }); 
+0

嘗試添加'async:false'作爲ajax請求的選項。當我需要維護ajax請求的順序時,我發現它很有幫助。它也可能適用於此。 – Lester 2012-01-27 22:37:51

+1

@Lester:這不是一個好建議。指定'async:false'會在請求期間鎖定瀏覽器。 – 2012-01-27 22:45:45

回答

7

你可以嘗試存儲XHR在一個變量,它與xhr參數您在AJAX成功回調得到比較。只有在兩者匹配時才調用響應函數。您也可以相應地調整「延遲」參數。

var lastXhr; 

$("#city").autocomplete({ 
    delay: 500, // 500ms between requests. 
    source: function(request, response) { 
     lastXhr = $.ajax({ 
      url: "/geo/json_autocomplete.php", 
      dataType: "json", 
      data: { 
       term: $("#city").val(), 
       countryid: $("#countryid").val() 
      }, 
      success: function(data, status, xhr) { 
       if (xhr === lastXhr) { 
        response($.map(data, function(item) { 
        //console.debug(item.value+" "+item.label+" "+item.id); 
         return { 
          label: item.label, 
          value: item.value, 
          id: item.id 
         }; 
        })); 
       } 
      } 
     }); 
    }, 
    minLength: 2, 
    delay: 500, 
    select: function(event, ui) { 
     $("#cityid").val(ui.item.id); 
     showForm(); 
    } 
}); 
+0

這很好。謝謝! – 2012-02-07 15:04:59