2012-04-04 91 views
4

我期待在jQuery UI的自動完成文件和尋找他們與緩存回調的例子:多個自動完成電話 - jQuery的

$(function() { 
    var cache = {}, lastXhr; 

    $('#Field').autocomplete({ 
     minLength: 2, 
     delay: 600, 
     source: function(request, response) { 
      var term = request.term; 

      if(term in cache) { 
       response(cache[term]); 
       return; 
      } 

      lastXhr = $.post('LoadData', function(data, status, xhr) { 
       cache[term] = data; 

       if(xhr === lastXhr) { 
        response(data); 
       } 
      }); 
     } 
    }); 
}); 

代碼線爲使用自動完成字段和存儲的緩存已被查詢的查詢。以下線使用,因此,如果一個查詢所用時間比另一個更不會更換自動完成值:

if(xhr === lastXhr) { 
    response(data); 
} 

如果我開始輸入幾個字母,它會向服務器查詢數據,然後我暫停並再次開始輸入,這將觸發另一次到服務器的旅程。 如果第一個查詢在第二個查詢後結束,那麼加載圖標永遠不會消失。我認爲這是因爲它永遠不會調用response()回調。有一種方法可以在第二次請求發出後取消第一次請求嗎?

回答

2

你可以直接在添加lastXhr.abort()之前嗎?這會在每次開始新請求時取消先前的請求。

$(function() { 
    var cache = {}, lastXhr; 

    $('#Field').autocomplete({ 
     minLength: 2, 
     delay: 600, 
     source: function(request, response) { 
      var term = request.term; 

      if(term in cache) { 
       response(cache[term]); 
       return; 
      } 

      // Abort previous access if one is defined 
      if (typeof lastXhr !== 'undefined' && lastXhr.hasOwnProperty("abort")) { 
       lastXhr.abort(); 
      } 

      lastXhr = $.post('LoadData', function(data, status, xhr) { 
       cache[term] = data; 

       if(xhr === lastXhr) { 
        response(data); 
        // Set to undefined, we are done: 
        // helps when deciding to abort 
        lastXhr = undefined; 
       } 
      }); 
     } 
    }); 
}); 
+0

這並不永遠旋轉停止自動完成加載圖標。 – Dismissile 2012-04-04 19:59:06

+0

什麼代碼停止微調? – 2012-04-04 20:16:46

+0

調用響應()。但我不想調用'response(null)',因爲它會清除列表。需要能夠以某種方式告訴自動完成調用已完成而不會覆蓋數據。 – Dismissile 2012-04-04 20:21:21

1

將最終結果與請求一起緩存。然後,您可以確保每次都調用響應回調,並且lastData將確保使用正確的數據,而不管查詢是否不同步。

如:

$(function() { 
    var cache = {}, lastXhr,lastData; 

    $('#Field').autocomplete({ 
     minLength: 2, 
     delay: 600, 
     source: function(request, response) { 
      var term = request.term; 

      if(term in cache) { 
       response(cache[term]); 
       return; 
      } 

      lastXhr = $.post('LoadData', function(data, status, xhr) { 
       cache[term] = data; 

       if(xhr === lastXhr) { 
        response(data); 
        // Store the latest data 
        lastData = data; 

       } 
       else 
       { 
        // Queries have come back out of sync - this isn't the last one 
        // but we need to call response to stop the spinner 
        response(lastData); 
       } 
      }); 
     } 
    }); 
});