2017-02-03 54 views
0

我想填充引導自動完成(Typeahead)列表與外部Web服務提供的數據,在這種情況下,「Wunderground天氣」,但它不工作。Typeahead Autocomplete AJAX

它返回一個錯誤,說「hasOwnProperty」。

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> 

<!-- Latest compiled and minified JavaScript --> 
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script> 

<script src="bootstrap-typeahead.js"></script> 

HTML

<div class="col-md-12"> 
    <h1>Search Dynamic Autocomplete using Bootstrap Typeahead JS</h1> 
    <input class="typeahead form-control" type="text"> 
</div> 

JQuery的

$(".typeahead").typeahead({ 
    source: function (query,process) { 
       return process(autoCompleteWunderGround(query)) 
      } 
}); 


function autoCompleteWunderGround(query){ 
    var results = [] 
    $.ajax({ 
     url : "http://autocomplete.wunderground.com/aq?query=query", 
     dataType : "jsonp", 
     jsonp : "cb", 
     data : { 
     "query" : query, 
     "format" : "JSON", 
     }, 
     success : function(data) { 
      $.each(data.RESULTS, function(index, value){ 
       results.push(value.name) 
      }) 
     } 
    }); 

    return results; 

} 

感謝

回答

0

我認爲這個問題是在功能autoCompleteWunderGround()的返回。 Ajax是異步的,因此函數的返回在成功之前執行。數組結果永遠不會被填充。 您可以嘗試使用回調函數。

+1

你是什麼意思?你能提供一個例子嗎?謝謝 –