I want to create a JSON array like this:
var ddBasic = [
{ text: "Facebook", value: 1, },
{ text: "Twitter", value: 2, },
{ text: "LinkedIn", value: 3, },
{ text: "Foursquare", value: 4, }
];
I’m using data from last.fm, so it would be something like this:
var tags = [
{ text: "rock", value: "rock", },
{ text: "pop", value: "pop", },
];
It needs to have a comma at the end so the ddslick dropdown function ignores the imageSrc and other things it can use for a dropdown, other it throws this error:
Uncaught TypeError: Cannot read property 'imageSrc' of undefined
To tie everything together, I have:
$('#tag').ddslick({
data: tags,
onSelected: function(selectedData) {}
});
This is the function that gets the tags:
var tags = [];
var getTopTracks = function () {
$.getJSON(
settings.PHP_REQUEST_URL, {
method: "tag.getTopTags",
api_key: settings.LASTFM_APIKEY,
format: "json",
},
function (data) {
var limit = 50;
data.toptags.tag.sort(function (t1, t2) {
return t2.count - t1.count;
});
$.each(data.toptags.tag, function (i, item) {
if (i > limit) return false;
console.log(item.name);
tags.push({
text: item.name,
value: item.name
});
});
});
};
// event handlers (load quando o form é invocado só)
getTopTracks();
alert(tags.length);
// define tema para a combobox
$('#tag').ddslick({
data: tags,
onSelected: function (selectedData) {}
});
How can I accomplish this?
At the point you use the alert it’s very likely
tagsis not filled as$.getJSON()is an asynchronus request, meaning the request will be handled in the background and execution of the script continues. You have to use the callback method as you already did for filling up the array.http://api.jquery.com/jQuery.getJSON/