To download data once:
Assumptions:
You have a REST API endpoint in / services that serves an array of JSON objects
The array contains objects that have at least the attribute "name" and "id". Example:
[{"id": 0, "name": "Foo"}, {"id": 1, "name": "Bar"}]
You want to save this array as a global 'services_raw'
Firstly, our function for loading data and creating a global "services_raw" (AKA "window.services_raw"):
fetchFromAPI = function() { console.log("fetchFromAPI called"); var jqxhr = $.ajax( { dataType:'json', type: 'GET', url: "/services", success: function(data, textStatus, jqXHR) { services_raw = data; console.log("rosetta.fn.fetchServicesFromAPI SUCCESS"); rosetta.fn.refreshServicesSelect(); }, error: function(jqXHR, textStatus, errorThrown) { console.log("Error inside rosetta.fn.fetchServicesFromAPI", errorThrown, textStatus, jqXHR); setTimeout(rosetta.fn.fetchServicesFromAPI(), 3000);
Secondly, our selection code is Select2, which converts our data to a format that Select2 can select:
refreshServicesSelect = function () { // ref: http://jsfiddle.net/RVnfn/2/ // ref2: http://jsfiddle.net/RVnfn/101/
Here, what the Select2 element in HTML should look like before your call above:
<input id="add-service-select-service" type="hidden" style="width:100%">
To use all of this, call (in JS):
window.fetchFromAPI(); window.refreshServicesSelect();
Finally, here is JSFiddle where you can play with a similar thing: http://jsfiddle.net/RVnfn/102/
Basically, in my example above, we just use ajax to populate the equivalent of window.pills in Fiddle.
Hope this helps :)
Answer if you know how to do this using the Select2.ajax function, as this will be a little shorter.
seanp2k
source share