最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Jquery : how to add <li> in an existing <ul> with json data - Stack Overflow

programmeradmin4浏览0评论

I have code that looks like this:

<div id="tags">
  <ul>
  </ul>
</div>

and I'd like to append some items to the list using json data

 $.getJSON("data.json", function (data) {
            var html = '';
            var len = data.tags.length;
            for (var i = 0; i < len; i++) {
                html += '<li><a href="#">' + data.tags[i].tag + '</a></li>';
            }

            $("#tags ul").append(html);


        })
        .done(function () {
            console.log("second success");
           })
       .fail(function(err){console.log(err)});

but nothing happens , where is my mistake?

I have code that looks like this:

<div id="tags">
  <ul>
  </ul>
</div>

and I'd like to append some items to the list using json data

 $.getJSON("data.json", function (data) {
            var html = '';
            var len = data.tags.length;
            for (var i = 0; i < len; i++) {
                html += '<li><a href="#">' + data.tags[i].tag + '</a></li>';
            }

            $("#tags ul").append(html);


        })
        .done(function () {
            console.log("second success");
           })
       .fail(function(err){console.log(err)});

but nothing happens , where is my mistake?

Share Improve this question asked May 26, 2014 at 22:14 KlausKlaus 412 silver badges3 bronze badges 9
  • 1 What error messages do you see in your browser's console? – Terry Commented May 26, 2014 at 22:15
  • 1 Could you provide a sample of the JSON returned by your call to data.json? – Nathan Apple Commented May 26, 2014 at 22:17
  • can you post a fiddle with your code? – faby Commented May 26, 2014 at 22:20
  • We don't need off-site demos. You need to give enough information to reproduce the issue, along with error messages in the console. – cookie monster Commented May 26, 2014 at 22:24
  • @cookiemonster Yes,you're right I'm sorry. – Klaus Commented May 27, 2014 at 8:39
 |  Show 4 more ments

3 Answers 3

Reset to default 6

Your Approach

Your code will work fine as long as the JSON structure in your data.json is in the following format -

{
"tags": [
    {
        "tag": "Tag1"
    },
    {
        "tag": "Tag2"
    },
    {
        "tag": "Tag3"
    },
    {
        "tag": "Tag4"
    }
]
}

Suggested Approach

If your JSON is in this structure -

{
"tags": [
    "Tag1",
    "Tag2",
    "Tag3",
    "Tag4"
]
}

The javascript to make it work would be -

$(document).ready(function(){
    $.getJSON( "data.json", function( data ) {
        var items = '';
        $.each( data.tags, function( key, val ) {
            items += '<li id="' + key + '"><a href="#">' + val + '</a></li>';
        });
        $("#tags ul").append(items);
    }).done(function () {
        console.log("Success");
    }).fail(function(err){
        console.log(err)
    });
});

This will generate the following HTML in your DOM -

<div id="tags">
    <ul>
        <li id="0"><a href="#">Tag1</a></li>
        <li id="1"><a href="#">Tag2</a></li>
        <li id="2"><a href="#">Tag3</a></li>
        <li id="3"><a href="#">Tag4</a></li>
    </ul>
</div>

working fiddle with test json

http://jsfiddle/BWM2E/1/

$.getJSON("http://query.yahooapis./v1/public/yql?q=select%20%2a%20from%20yahoo.finance.quotes%20WHERE%20symbol%3D%27WRC%27&format=json&diagnostics=true&env=store://datatables/alltableswithkeys&callback", function (data) {

    var html = '';
            var len = data.query.count;

    for (var i = 0; i < len; i++) {
                html += '<li><a href="#">' + data.query.created + '</a></li>';
            }

            $("#tags ul").append(html);


        })


        .done(function () {
            console.log("second success");
           })
       .fail(function(err){console.log(err)});

in for loop I print always created property because there is only one query element

the part of the json that I have treated is the following

{"query":{"count":1,"created":"2014-05-26T22:23:03Z"}}

in your case the problem is the url of json that make a redirect.

test it in this (then click on "make a request") site and see this message error that explain you the problem

We weren't able to successfully make a request to http://myjtest.altervista/tagcloud/data.json.

This is likely because of a Cross-site HTTP request and your server not having the appropriate Access-Control-Allow-Origin and Access-Control-Allow-Methods headers.

Looks like your json file is invalid.
Maybe you use single quotes instead of double quotes or something else. Check your data.json file.
According to your js code, your file data.json should be like this:

{
    "tags":[
        {"tag":"name1"},
        {"tag":"name2"},
        {"tag":"name3"}
    ]
}
发布评论

评论列表(0)

  1. 暂无评论