2011-03-02 38 views
0

我在自動完成時遇到問題,因爲它只返回一條記錄,而遠程web服務正在返回10條記錄。jquery ui自動完成只返回一個值

想知道你是否可以看看我的代碼,看看我是否做錯了什麼?

接收的數據:

{ 「d」: 「[\」 02102008633 \」,\ 「02102008794 \」,\ 「02102008980 \」,\ 「02102015321 \」,\ 「02102018743 \」, \ 「02102024602 \」,\ 「02102037454 \」,\ 「02102038366 \」,\ 「02102040774 \」,\ 「02102056369 \」]「}

jQuery(txtDestination).autocomplete({ 
      minLength: 2, 
      source: function (request, response) { 
       jQuery.ajax({ 
        url: "/SearchService.asmx/GetDestinationAutocompleteValue?" + "accountCode=" + accountCode.toString() + "&criteria=" + jQuery(txtDestination).val().toString(), 
        data: "{}", 
        type: "GET", 
        contentType: "application/json; charset=utf-8", 
        success: function (data) { 
         if (data != null && data.hasOwnProperty('d') && eval(data.d) != null) { 
          var result = new Array(eval(data.d)); 
          response(jQuery.map(result, function (item, ctr) { 
           return { label: item[ctr], id: item[ctr], value: item[ctr] } 
          })); 
         } 
        }, 
        error: function (XMLHttpRequest, textStatus, errorThrown) { alert(textStatus + " " + errorThrown); } 
       }); 
      } 
     }); 

萬分感謝!

乾杯, 安

+0

JQuery.map的結果是什麼樣的? – Marco 2011-03-02 23:23:25

+1

除了Xavier的正確答案外,請重新閱讀http://jqueryui.com/demos/autocomplete/的「概述」部分,具體來說,你應該總是**調用'response()'(你不需要在你的錯誤處理中這樣做),你應該(如果可能的話)從服務器返回有效的json對象數據,所以你不會被迫像這樣''eval()' – davin 2011-03-02 23:32:30

+0

感謝提示@davin!將嘗試再次審查這個! :) – mallows98 2011-03-02 23:46:06

回答

1

我想我找到了......看看這一行:

var result = new Array(eval(data.d)); 

現在,由於eval(data.d)計算結果爲數組已經,你基本上叫什麼像這樣:

var result = new Array([1, 2, 3]); 

將實際創建一個長度的陣列 - 第一元件,其是長度爲三的陣列。這傻了眼了我,直到我以爲要檢查它在JS控制檯(不要讓我開始在打印輸出上不包括方括號...):

js> ra1 = new Array(1, 2, 3) 
1,2,3 
js> ra2 = new Array([1, 2, 3]) 
1,2,3 
js> ra1.length 
3 
js> ra2.length 
1 

但好消息是,有一個簡單的修復:

var result = eval(data.d); 

希望這有助於!

+0

謝謝Xavier!這確實解決了我的問題! :) – mallows98 2011-03-02 23:45:31

+0

@ mallows98很高興我能幫助 - 歡呼! – 2011-03-02 23:57:22