2016-12-29 85 views
1

所以我使用了使用jQuery-Autocomplete我的數據庫中的AJAX自動完成,這是我當前的代碼:jQuery的自動完成和角度HTTP返回錯誤

HTML:

<input ng-keyup="searchCustomer()" id="customerAutocomplete" type="text"> 

$scope.searchCustomer = function() { 
     $http.get('/api/customers') //this is a json return 
      .then(function (response) { 
       console.log(response.data); //FIRST OUTPUT 
       $('#customerAutocomplete').autocomplete({ 
        lookup: response.data, 
        onSelect: function (suggestion) { 
         console.log(response); 
        } 
       }); 
      }, function (error) { 
       console.log(error) 
      }) 
    } 

我的控制檯輸出每當我輸入的東西是這樣的:

enter image description here

正如你所看到的,它返回的console.log但有一個錯誤,有沒有自動完成的表現。

jQuery-Autocomplete的使用部分,有我曾嘗試過的部分和它的工作。

var countries = [ 
    { value: 'Andorra', data: 'AD' }, 
    { value: 'Zimbabwe', data: 'ZZ' } 
]; 

$('#autocomplete').autocomplete({ 
    lookup: countries, 
    onSelect: function (suggestion) { 
     alert('You selected: ' + suggestion.value + ', ' + suggestion.data); 
    } 
}); 

但是,無論何時我從http調用更改自己的數據的國家變量,我仍然收到錯誤。

我查庫

enter image description here

線85和它的return suggestion.value.toLowerCase().indexOf(queryLowerCase) !== -1;

所以我的第一個猜測是JSON.stringifyresponse.data,然後我得到這個:

enter image description here

所以它沒有工作過。任何幫助將非常感激..

回答

0

按照從服務器jQuery-Autocompletedocumentation反應必須是JSON格式以下JavaScript對象如下:

{ 
    // Query is not required as of version 1.2.5 
    "query": "Unit", 
    "suggestions": [ 
    { "value": "United Arab Emirates", "data": "AE" }, 
    { "value": "United Kingdom",  "data": "UK" }, 
    { "value": "United States",  "data": "US" } 
    ] 
} 

或者你需要使用transformResult函數來分析你的API響應標準迴應。

我想,你的情況應該是象下面這樣:

// HTML

<input id="customerAutocomplete" type="text"> 

//腳本

$('#customerAutocomplete').autocomplete({ 
    serviceUrl : '/api/customers', // your full api URL 
    onSelect: function (suggestion) { 
    console.log(response); 
    }, 
    transformResult: function(response) { 
    if(response.data.length > 0) { 
     return { 
     suggestions: $.map(response.data, function(dataItem) { 
      return { value: dataItem.customer_name, data: dataItem.customer_id }; 
     }) 
     }; 
    } else { 
     return {}; 
    } 
    } 
}); 
+0

現在,我得到無法讀取的未定義的屬性 '長度' – FewFlyBy

+0

在這個部分意見建議:$ .map(response.data,function(dataItem) – FewFlyBy

+0

我已經更新了我的答案,因爲我認爲不需要'searchCustomer'函數,所以請相應地進行其他更改。 – ranakrunal9