简体   繁体   中英

JSON to HTML not rendering into HTML via ID

I am using PHPstorm IDE and i'm trying to render the following JSON and it gets stuck showing only the <ul></ul> without spitting the <li>'s into HTML the each function. Any idea what could be the issue?

thanks.

Script.js:

$(function(){
    $('#clickme').click(function (){
        //fetch json file
        $.ajax({
            url:'data.json',
            dataType: 'json',
            success: function(data){
                var items = [];
                $.each(data, function (key, val) {
                    items.push('<li id=" ' + key + '">' + val + '</li>');
                });
                $('<ul/>', {
                    'class': 'tasks',
                    html: items.join('')
                }).appendTo('body');
            },
            statusCode: {
                404: function(){
                    alert('there was a problem with the server. try again in a few secs');
                }
            }
        });

    });
});

And the JSON:

{"id":"1","mesi":"mesima 0","done_bool":"1"},{"id":"2","mesi":"mesima 1","done_bool":"0"},{"id":"3","mesi":"mesima 2 ","done_bool":"1"},{"id":"4","mesi":"mesima 3","done_bool":"1"}

My HTML is just an a href that spits out the click ID:

<a href="#" id="clickme">Get JSON</a>

Try like this:

success: function(data){
            var items = '';
            $.each(data, function (key, val) {
                items += '<li id=" ' + key + '">' + val + '</li>';
            });
            ul = $('<ul/>').html(items);
             $('body').append(ul);
        }

for multiple objects

success: function(datas){
            var items = '';
           $.each(datas, function (i,data) {
                $.each(data, function (key, val) {
                    items += '<li id=" ' + key + '">' + val + '</li>';
                });
            });
            ul = $('<ul/>').html(items);
             $('body').append(ul);
        }

output

<ul>
    <li id=" id">1</li>
    <li id=" mesi">mesima 0</li>
    <li id=" done_bool">1</li>
    <li id=" id">2</li>
    <li id=" mesi">mesima 1</li>
    .
    .
</ul>
<script>
$(document).ready(function(){
    $("button").click(function(){
        $.getJSON("demo_ajax_json.js", function(result){
            $.each(result, function(i, field){
                $("div").append(field + " ");
            });
        });
    });
});
</script>

<button>Get JSON data</button>

By Using this Method You can Easily get Your JSON value In HTML

Try this one :)

  $.ajax({
            url: 'data.json',
            dataType: 'json',
            success: function(data){

                var html = "<ul>";
                items = data.map(function(obj){
                   html += "<li id='" + obj.id + "'>" + obj.mesi + "</li";
                });
                html += "</ul>";

                $('body').append(html);

I would try with some like this

$(function(){
    $('#clickme').click(function (){
        //fetch json file
        $.ajax({
            url:'data.json',
            dataType: 'json',
            success: function(data){

                // uncomment line below if data is a single JSON     
                // data = [data]

                var items = [];

                // we create a list where we will append the items
                var list = document.createElement("ul");

                data.forEach(function(item){

                    // we create a list item 
                    var listItem = document.createElement("li");

                    // we set the attributes
                    listItem.setAttribute("id", item.id ); // item.id or the property that you need 

                    // we add text to the item
                    listItem.textContent = item.mesi;

                    // We append the list item to the list
                    list.appendChild(listItem);

                });
                // we append the list to the body
                $("body").html(list);

            },
            statusCode: {
                404: function(){
                    alert('there was a problem with the server. try again in a few secs');
                }
            }
        });

    });
});

Try like this:

 $(function() {
    $('#clickme').click(function() {
        // fetch json file
        $.ajax({
            url : 'data.json',
            dataType : 'json',
            // please confirm request type is GET/POST
            type : 'GET',
            success : function(data) {
                // please check logs in browser console
                console.log(data);
                var ulHtml = "<ul>";
                $.each(data, function(key, obj) {
                    ulHtml += '<li id="' + obj.id + '">' + obj.mesi + '</li>';
                });
                ulHtml += "</ul>";
                // please check logs in browser console
                console.log(ulHtml);
                $('body').append(ulHtml);
            },
            error : function(jqXhr, textStatus, errorThrown) {
                console.log(errorThrown);
                alert(textStatus);
            }
        });
    });
});


<button id="clickme">Get JSON data</button>

I log json data and created ul html, Please check logs in browser console

I'm not sure how you want to output each item, so I made a simple suggestion, you can easily change the HTML to what you need. Here is working code:

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
</head>
<body>
<a href="#" id="clickme">Get JSON</a>
<script>
$(function() {
  $('#clickme').click(function() {
    //fetch json file
    $.ajax({
      url: 'data.json',
      dataType: 'json',
      success: function(data) {            
        var items = [];
        $.each(data, function(key, val) {
          // the HTML output for each item
          var done = (val.done_bool === '1') ? 'true' : 'false';
          items.push('<li id=" ' + val.id + '">' + val.mesi + ': ' + done + '</li>');
        });
        $('<ul/>', {
          'class': 'tasks',
          html: items.join('')
        }).appendTo('body');
      },
      statusCode: {
        404: function() {
          alert('there was a problem with the server. try again in a few secs');
        }
      }
    });

  });
});
</script>
</body>
</html>

data.json

[{"id":"1","mesi":"mesima 0","done_bool":"1"},{"id":"2","mesi":"mesima 1","done_bool":"0"},{"id":"3","mesi":"mesima 2 ","done_bool":"1"},{"id":"4","mesi":"mesima 3","done_bool":"1"}]

I also created a __jsfiddle__ so you can test it directly. (The AJAX call is simulated with the Mockjax library): https://jsfiddle.net/dh60nn5g/

Good to know:
If you are trying to load the JSON from another domain, you may need to configure CORS (Cross-origin resource sharing):
https://en.wikipedia.org/wiki/Cross-origin_resource_sharing

Isn't this supposed to be a GET request? i think you are missing the method on your Ajax request. You should add

method: 'GET'

to your ajax request. I think this is a big deal in making ajax request.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM