简体   繁体   中英

How to put result into DIV from JSON?

From the below function I am getting results. Now I want to put that result into a div. So how should I put the result into a div?

$(document).ready(function () {
    $.ajax({
        type: "POST",
        url: "../ajaxaction.php",
        data: {
            action: 'alllist'
        },
        dataType: 'json',
        success: function (msg) {
            for (var i = 0; i < msg.length; i++) {
                var uname = msg[i].user_name;
                var vtitle = msg[i].video_title;
                var vid = msg[i].video_id;
                var vthumb = msg[i].video_thumb;
            }
        }
    });

});

You can append the result in to div with the format you like but a simple way of adding would be. You can use append() function to keep the added html with new html for each iteration of loop.

  success: function(msg){ 
       for (var i = 0; i < msg.length; i++) { 
        var uname = msg[i].user_name;
        var vtitle = msg[i].video_title;
        var vid = msg[i].video_id; 
        var vthumb = msg[i].video_thumb;
         $('#divId').append("Name: " + uname + "," + "Title: " + vtitle +
                            "Id: " + vid + "," + "Thumb: " + vthumb + "<br />");
       }
$(document).ready(function() { 
    $.ajax({
       type: "POST",
       url: "../ajaxaction.php",
       data: { action:'alllist'},
       dataType: 'json',
       success: function(msg){ 
       for (var i = 0; i < msg.length; i++) { 
        var uname = msg[i].user_name;
        var vtitle = msg[i].video_title;
        var vid = msg[i].video_id; 
        var vthumb = msg[i].video_thumb;

        $("#container").html("Username: " + uname + "<br />Video Title: " + vtitle + "<br />Vide ID: " + vid + "<br />Video Thumb: " + vthumb);
       }


   }});

});

If your div exists:

jQuery('div selector').append(uname+' '+vtitle+...whatever variable and format);

If not

jQuery('element selector to put the div in').append('<div id="aID" class="some classes">'+uname+' '+vtitle+...whatever variable and format...+'</div>');

you can do this:

success: function(msg){ 
   $.each(msg, function(i, item){
      $('#divid').html('User Name : '+item.user_name+ 
                       'Video title : '+item.video_title+
                       'Video Id : 'item.video_id+
                       'Video Thumb : 'item.video_thumb );
      });
}

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