2012-04-09 103 views
6

我在創建的頁面上使用jquery-ui自動完成功能。在同一頁面上,我正在進行一些Ajax事件。在其他ajax事件期間,我正在爲我的頁面添加一個疊加層,以便該網站上的所有鏈接不再可供用戶點擊。我不希望在自動填充過程中發生這種情況。

自動完成:

$(function() { 
    $("#search_input").autocomplete({ 
    source: '/search_autocomplete/',}); 
}); 

AJAX:

$.ajax({ 
    url: "/ajax_login/", 
      login_user: $("#login_user").val(), 
      password: $("#login_password").val(), 
      }); 

ajaxStart:

$("#loading_gif").ajaxStart(function() { 
    $("#overlay").show(); 
    $(this).show(); 
}); 

爲了防止ajaxstart功能從在阿賈克斯比賽時,就沒有必要執行。我加

global:false, 

到相應的ajaxfunctions。我怎樣才能在自動完成期間做類似的事情而不用改變jquery-ui源代碼?

回答

1

如果你想$.ajax()工作以某種方式的時間,但現在所有的時候,那麼你可能不應該改變其缺省行爲。

我建議創建一個函數,將ajax請求包裝在一個函數中,該函數在適當的時候啓用和禁用覆蓋。在要使用疊加層的地方調用此函數,並使用普通的$.ajax()作爲自動填充。

5

爲此,您必須省略與source的簡寫呼叫,然後像這樣更改呼叫。

$('#search_input').autocomplete({ 
    source: function (request, response) { 
     var DTO = { "term": request.term }; 
     //var DTO = { "term": $('#search_input').val() }; 
     $.ajax({ 
      data: DTO, 
      global: false, 
      type: 'GET', 
      url: '/search_autocomplete/', 
      success: function (jobNumbers) { 
       //var formattedNumbers = $.map(jobNumbersObject, function (item) { 
       // return { 
       //  label: item.JobName, 
       //  value: item.JobID 
       // } 
       //}); 
       return response(jobNumbers); 
      } 
     }); 
    } 
    //source: '/search_autocomplete/' 
}); 

這個長手方法的優點是

  1. 您可以通過多個參數。另外參數名稱不應該是術語。
  2. 簡寫符號需要一串字符串。在這裏你可以返回一個對象數組。
1

我同意naveen的回答是最好的解決方案。在我的情況下,需要更改的大量代碼不符合成本效益,因爲我們正在進行重寫,我們需要一個短期解決方案。

你可以重寫jQuery UI中的ajax調用,我複製處理AJAX請求的_initSource函數調用的源代碼。然後只需將全局:false添加到$ .ajax選項。這裏的代碼基於jquery-ui 1.9.2,您可能需要爲您的版本找到正確的源代碼。

$.ui.autocomplete.prototype._initSource = function() { 
    var array, url, 
     that = this; 
    if ($.isArray(this.options.source)) { 
     array = this.options.source; 
     this.source = function(request, response) { 
      response($.ui.autocomplete.filter(array, request.term)); 
     }; 
    } else if (typeof this.options.source === "string") { 
     url = this.options.source; 
     this.source = function(request, response) { 
      if (that.xhr) { 
       that.xhr.abort(); 
      } 
      that.xhr = $.ajax({ 
       url: url, 
       data: request, 
       dataType: "json", 
       global: false, 
       success: function(data) { 
        response(data); 
       }, 
       error: function() { 
        response([]); 
       } 
      }); 
     }; 
    } else { 
     this.source = this.options.source; 
    } 
};