Good practice when loading a div with database data, using jQuery

Asked

Viewed 136 times

1

What is the best way to build a div with jQuery Example:

$(document).ready(function(){
$.ajax({
    type:'post',        
    dataType: 'json',   
    url: 'listAllForum',
    success: function(dados){
        for(var i = 0; dados.length > i; i++){

            $('#post-forum').append('<strong>Usuario Fulano de Tal</strong> - Data: 00/00 <br>' + 
                    dados[i].idForum + ' - '+ dados[i].message + '<br> <br>');
        }
    }
});

});

For example: I want each message to have a different color to make it easier to read. The user name puts the tags to give a highlight, but is it right to do so within the ajax’s for ? If I wanted to put a link to redirect to a @Requestmapping, where I would put href ?

  • It would be more interesting to create a specific function to work with the data if you wanted to do it this way. But, in my opinion, it would be better to use template-Engines, for example: http://handlebarsjs.com/ . because then you would already leave the code ready and easier to maintain.

  • Good afternoon, I’m starting now, how could I mount a separate Function to remove HTML from inside jQuery ?

1 answer

0

Since you don’t use a template-teach, the best way would be to add some color classes in your CSS, and after the ajax request you return in your json object the right color for each post.

$(Document). ready(Function(){ $. ajax({ type:'post',
dataType: 'json',
url: 'listAllForum', Success: Function(data){ for(var i = 0; data.length > i; i++){

        //Get cores
        var varCor = dados.cor;
        var contentPosts =  $('#post-forum');         

        contentPosts.append('<div class="' +  varCor + '">Usuario Fulano de Tal</strong> - Data: 00/00 <br>' + 
                dados[i].idForum + ' - '+ dados[i].message + '</div>');
    }
}

});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.