如何在JQuery中创建JSON数组?

时间:2012-10-13 16:55:56

标签: jquery arrays json

我想创建一个像这样的JSON数组:

var ddBasic = [
    { text: "Facebook", value: 1, },
    { text: "Twitter", value: 2, },
    { text: "LinkedIn", value: 3, },
    { text: "Foursquare", value: 4, }
];

我正在使用来自last.fm的数据,所以它会是这样的:

var tags = [
        { text: "rock", value: "rock", },
        { text: "pop", value: "pop", },
    ];

它最后需要一个逗号,所以ddslick下拉函数会忽略imageSrc以及它可用于下拉列表的其他东西,其他它会抛出此错误:

Uncaught TypeError: Cannot read property 'imageSrc' of undefined

为了把所有东西捆绑在一起,我有:

$('#tag').ddslick({
    data: tags,
    onSelected: function(selectedData) {}   
});

这是获取标签的函数:

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) {}
});

我该如何做到这一点?

1 个答案:

答案 0 :(得分:2)

var tags = []; //initialised tags with length 0
getTopTracks(); //fetching date in background (!)
alert(tags.length); //running while data is still fitched (unless you've a 0ping connection => alerting length 0

在您使用警报的时候,tags很可能未被填充,因为$.getJSON() asynchronus 请求,这意味着请求将在后台处理并执行脚本继续。你必须像使用填充数组那样使用回调方法。

This, getJSON, is a shorthand Ajax function, which is equivalent to:
$.ajax({   
   url: url,
   dataType: 'json',
   data: data,
   success: callback
});

http://api.jquery.com/jQuery.getJSON/

//getJSON success callback:
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
        });
    });
    //alert the length AFTER the tags been pushed
    alert(tags.length);

    // define tema para a combobox   
    $('#tag').ddslick({
        data: tags,
        onSelected: function (selectedData) {}
    });
}