Frage

I'm starting with Select2. I want to combine "Tagging Support" and "Loading remote data" (see http://ivaynberg.github.io/select2/).

In the body of an HTML file, I presently have an input form:

<input id="topics">

with "Tagging Support" using a list of tags given by an array, as the following script of the head of the HTML file shows:

$("#topics").select2({
     placeholder: "Choose topic(s)",    
     tags:["russia", "europe", "obama"]
}); 

I also have a server, made in Node.js using Express, that is connected to a database. I know how to handle requests (POST or GET) on the server side, in connection with the database.

For the input form of my HTML file, I want, instead of the array ["russia", "europe", "obama"], to use an array of data provided by the server.

How could I write it?

Thanks!

War es hilfreich?

Lösung

Backend

You'll have to create a short route like this:

app.get('/foo/bar.json', function(req, res){
     //...
     res.send(data);
}

Frontend

$("#topics").select2({
    placeholder: "Search for a movie",
    minimumInputLength: 1,
    ajax: { // instead of writing the function to execute the request we use Select2's convenient helper
        url: "/foo/bar.json",
        dataType: 'json',
        results: function (data, page) { // parse the results into the format expected by Select2.
            // since we are using custom formatting functions we do not need to alter remote JSON data
            return {results: data};
        }
    },
});

And a JSON object can be/contain arrays. See https://ivaynberg.github.io/select2/#data

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top