简体   繁体   中英

Can I use jquery ajax response for Autocomplete

It's 3am. I've been banging my head against the wall for hours on this and just don't get it.

I'm trying to use jQuery autocomplete with the source data coming from an ajax request. Ajax seems to be working great, but I can't seem to use the response for the source data. Anonymous function fetches data on ready. Success calls test(response) passing the data to the function with autocomplete. The response looks exactly like the sample code. And when I paste my response from the console it works perfectly. But it will not let me use the variable 'albums' for the source.

$(function(){

    $.ajax({
        dataType: 'text',
        type: 'POST',
        url: '/albums/fetch_albums',
        success: function(response){
            console.log(response); // logs ["Italy","Hawaii"] -as expected
            test(response);
        }
    });

});

function test(data){
    var albums = data;
    console.log(albums);         // logs ["Italy","Hawaii"] - as expected
    console.log(typeof albums);  //logs string - as expected

   $('#autocomplete').autocomplete({
        source: albums,                //this is what I want... errors out.
        //source: ["Italy","Hawaii"] // pasted response if un-commented works fine.
    });
}

Here is the error message.

 GET http://journal.localhost.com/[%22Italy%22,%22Hawaii%22]?term=h 403 (Forbidden)jquery-2.1.1.min.js:4 n.ajaxTransport.k.cors.a.crossDomain.sendjquery-2.1.1.min.js:4 n.extend.ajaxjquery-ui.min.js:7 e.widget._initSource.e.isArray.string.options.source.sourcejquery-ui.min.js:7 e.widget._searchjquery-ui.min.js:6 (anonymous function)jquery-ui.min.js:7 e.widget.searchjquery-ui.min.js:6 (anonymous function)jquery-ui.min.js:7 (anonymous function)jquery-ui.min.js:6 i

There has to be a way to fetch data from the database and feed it to this function.

Help me Obiwan!

$(function(){

$.ajax({
    dataType: 'text',
    type: 'POST',
    url: '/albums/fetch_albums',
    success: function(response){
        console.log(response); // logs ["Italy","Hawaii"] -as expected
        var arrResponse = JSON.parse(response); //convert json object to array 
        test(arrResponse);
    }
});

});

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