jQuery loop through json?

2019-06-17 06:40发布

I have some json (var data)that looks like this:

{"success":"true","keywords":["firstkeyword","secondkeyword"]}

And im trying to loop through the keywords using this code:

            data.keywords.each(function(e){
                $('#campaign_keywords').append("<p>"+e+"</p>");
            });

But i get the error

Uncaught TypeError: Object firstkeyword,secondkeyword has no method 'each' 

标签: jquery json each
3条回答
爷的心禁止访问
2楼-- · 2019-06-17 06:59

You need to loop through it like this:

$.each(data.keywords, function (i, v) {
    $('#campaign_keywords').append("<p>"+data.keywords[i]+"</p>");
});

jQuery.each()

查看更多
祖国的老花朵
3楼-- · 2019-06-17 07:00

Its a javascript array, not jQuery object. just apply $ over it to make it jquery object like

    $(data.keywords).each(function(e){
        $('#campaign_keywords').append("<p>"+e+"</p>");
    });
查看更多
狗以群分
4楼-- · 2019-06-17 07:11

That's because it's an array and it needs to be a jquery wrapped object in order to use jquery functions. Try:

$.each(data.keywords, function(index, value){...});
查看更多
登录 后发表回答