jQuery jQuery.ajax({ url:'./...">

Creating a UL populated with JSON keys and values ​​using jQuery

I have it.

HTML

<div id="catcher"></div>

jQuery

jQuery.ajax({
  url:'./ajax.html', 
  async: true, 
  success: function(response){
    for (var key in response){
      jQuery('#catcher')
        .append("<ul>"+ key +"<li>" + response[key].toString() + "</li></ul>");
    }
  }
})

JSON looks like

{
    "Item":"Item Name",
    "Item 1":"Item Name",
    "Item 2":"Item Name",
    "Item 3":"Item Name",
    "Item 4":"Item Name"
}

I would like to do UL as follows

  • Paragraph
    • Element name
  • Paragraph 1
    • Element name

Etc. What I get now is each individual letter of the object value and number for the key. Instead, I want them both to be equal to the lines.

+4
source share
5 answers

You should try adding console.log(response)to your callback. This will probably show that responseis a string, not an object.

dataType:'json' jQuery.ajax(...), : json- jquery/javascript?

+3

. looped append <ul>, , :

var data = {
  "Item": "Item Name",
  "Item 1": "Item Name",
  "Item 2": "Item Name",
  "Item 3": "Item Name",
  "Item 4": "Item Name"
}

$('#catcher').append('<ol></ol>');

for (var key in data) {
  $('#catcher ol').append('<li>' + key + '<ul><li>' + data[key] + '</li></ul></li>');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="catcher"></div>
Hide result
+2
    jQuery.ajax({
      url: './ajax.html',
      async: true,
      success: function(response) {
        var ol = "<ol>";
        for (var key in response) {
          ol += "<li>" + key + "<ul><li>" + response[key] + "</li></ul>" + "</li>";
        }
        ol += "<ol>";
        jQuery('#catcher').append(ol);
      }
    });
+1

. , :

   jQuery.ajax({url:'./ajax.html', async: true, success: function(response){

                        var addcode=" ";
                        var i=1;

                        $.each(response, function(key,value) {

                                addcode +=  '<ul>' + (i++)  + '. ' + key;
                                addcode += '<li>' + value + '</li>';
                                addcode += '</ul>';

                        });
                        jQuery('#catcher').html(addcode);
    }})    
+1

. json-.

$. each (response, function (key, value) {

alert ( + ":" + );

});

0

Source: https://habr.com/ru/post/1658501/


All Articles