开发者

loop through json string via java script

I have retrieved data from databas开发者_JS百科e and parsed it like this javascript

var categories = <?php echo json_encode($categories); ?>;

in source code categories variable has following values:

var categories = [{"id":"27","name":"john"},{"id":"8","name":"jack"}]

now I'm trying to loop through this array like this

$(document).ready(function(){
//alert(categories);
cats = jQuery.parseJSON(categories);

for (x in cats)
{
    alert(cats.name);
}
}

but I'm getting nothing. Where is the problem?


Try this.

$(document).ready(function(){
    for (x in categories)
    {
        alert(categories[x].name);
    }
}


Even though you're using json_encode what you are actually creating is a Javascript object. (JSON is a string that represents a Javascript object.) Since JSON syntax is valid Javascript syntax, this works fine.

Just remove the call to jQuery.parseJSON and loop through categories directly.


here is another working example, copy paste and try...

$(document).ready(function () {
        var categories = ['{ "id": "27", "name": "john" }', '{ "id": "8", "name": "jack"}'];
        for (i = 0; i < categories.length; i++) {
            var c = jQuery.parseJSON(categories[i])
            alert(c.name);
        }
    });
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜