2013-11-20 36 views
1

我在jQuery網站自動完成時找到的代碼工作出現問題>http://api.jqueryui.com/autocomplete/#example-1當我執行以下操作時,我能夠在自動完成輸入控件中看到自己的結果。 ...jQuery自動完成在字符串的任意位置搜索匹配

這裏是fetchResponse

var cachedResult = null; 
function fetchResponse(callback) { 
    if (cachedResult) { 
     alert("In cachedResult!"); 
     callback(cachedResult); 
    } 
    $.ajax({ 
     url: "FacilitiesAsync", 
     type: 'GET', 
     cache: false, 
     data: 'sourceDb=myDb', 
     dataType: 'json', 
     success: function (json) { 
      // call autocomplete callback method with results 
      alert("Second"); 
      var cachedResult = $.map(json, function (name) { 
       return { 
        label: name.label, 
        value: name.value 
       }; 
      }); 
      alert("Third");     
      callback(cachedResult); 
     }, 
     error: function (xmlHttpRequest, textStatus, errorThrown) { 
      $("#autocomplete").text(textStatus + ', ' + errorThrown); 
     } 
    }); 
} 

$(document).ready(function() { 

    $("#autocomplete").autocomplete({ 
     source: function (request, response) { 
      alert("First"); 
      fetchResponse(function (result) { 
       response(result); 
      }); 
     } 
    }); 
}); 

然而,當我嘗試和執行從jQuery網站,我沒有得到任何結果,在所有的例子中看到的功能。我希望過濾我的結果,以便用戶可以在文本框中輸入任何單詞,並且過濾了列表,而不僅僅是在開始時搜索,但我不確定RegEx。

更新代碼:我在輸入控件中看到結果,但它們從未過濾,並且在Firefox控制檯中出現'elems'未定義的錯誤。我知道這與我將響應(結果)傳遞給grep函數有關,但我不知道如何解決它。

$(document).ready(function() { 

    $("#autocomplete").autocomplete({ 
     source: function (request, response) { 
      fetchResponse(function (result) { 
       var matcher = new RegExp("^" + $.ui.autocomplete.escapeRegex(request.term), "i"); 
       response($.grep(response(result), function (item) { 
        return response(matcher.test(item.label)); 
       }));           
      }); 
     } 
    }); 
}); 

我在調用這個fetchedResponse,因爲我需要先獲取數據,這是可行的。當我不嘗試和過濾它時,我在輸入控件中看到數據。

請原諒我,我還是jQuery的新手。

+0

是什麼'fetchResponse'你能提供的代碼? – melc

+0

代碼已更新 –

回答

0

代碼需要如下修改,

JS

function fetchResponse(callback) { 
    setTimeout(function(){ 
     /*assuming this is result from ajax*/ 
     var tags = ["c++", "java", "php", "coldfusion", "javascript", "asp", "ruby"]; 
     callback(tags); 
    },2000); 
} 

$("#autocomplete").autocomplete({ 
    source: function (request, response) { 
     fetchResponse(function (result) { 
      var matcher = new RegExp("^" + $.ui.autocomplete.escapeRegex(request.term), "i"); 
      response($.grep(result, function (item) { 
       return matcher.test(item); 
      })); 
     }); 
    } 
}); 

http://jsfiddle.net/c5YMF/1

相關問題