質問

I'm new to Javascript and I'm trying to create an array to use for Autocomplete plugin. The plugin is working perfectly with the following code:

countries = new Array();
countries[0]='United States';

'use strict';


$('#autocomplete').autocomplete({
    lookup: countries,
    minChars: 2,
    onSelect: function (suggestion) {
        //I will put something here soon.
    }
});

But when I try to create an array from a text file, I can't create the array even though the code seems fine.

$.get('test.txt', function(data){
   var array = data.split(',');
   var i = 0;
   array.forEach(function(insert) {
   countries[i]=insert;
   i++;
   });
});

Any reason why it would not insert the data in the text file to the countries array? It seems to me that everything I do should work. By the way, no worries, the test.txt file is just fine (United States,Mexico).

Thanks ahead and have a great day.

役に立ちましたか?

解決

$.get is an asynchronous function, so by the time autocomplete method is executed, countries would have got no element from the file. So, move the autocomplete function to the callback of $.get like this

$.get('test.txt', function(data) {
    var array = data.split(',');
    $('#autocomplete').autocomplete({
        lookup: array,
        minChars: 2,
        onSelect: function(suggestion) {
            //I will put something here soon.
        }
    });
});

Also, you don't have to populate countries like you did in the question. You can simply pass the array returned by JavaScript's split function, as it is.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top