简体   繁体   中英

Typeahead Autocomplete AJAX

I'm trying to fill up the bootstrap autocomplete(Typeahead) list with data provided by an external Web-service, in this case "Wunderground Weather", but it's not working.

It's returnin an error saying "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;

}

Thanks

I think the problem is in the return of the function autoCompleteWunderGround(). Ajax is asynchronous so the return of the function is executet before the success. The array results it's never filled. You can try with a callback function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM