I would prefer the option with the first approach. But it depends on the type of generated HTML that you are now returning from the server side.
If this is a simple element, you can simply return the JSON object from the server with one of the properties that identify the element.
For example, a web service response would look like this:
{'elem': 'b', 'text': 'bold', 'value': '42'}
And you consume this in an AJAX call like this:
$.ajax({ datatype: "json", ... success: function(response) {
Where doit is a Javascript function that is already part of your client code base and you simply use the arguments returned by the web service.
Alternatively, if your generated HTML is a complex piece, you need to define common templates and use client-side templates to convert the returned data into a presentation.
For example, your client template might look like this:
<script type='text/template' id='tmpl'> <div><h3></h3><p></p><h5></h5></div> </script>
Your web service returns something like this:
{'title': 'title', 'text': 'paragraph', 'value': '42'}
And you consume this in an AJAX call like this:
$.ajax({ datatype: "json", ... success: function(response) { // clone the client-side template var template = $('#tmpl').html(), $elem = $(template); // append to your div $('#mydiv-2').append($elem); // populate the cloned template with returned object properties $elem.find('h3').text(response.title); $elem.find('p').text(response.text); $elem.find('h5').text(doit(response.value)); } });
This way you avoid returning generated HTML from your server and managing presentation data only on the client side. Your web service does not need to know presentation aspects and deals only with raw data (consumption or eruption). The client code receives data from the web service and is engaged in the use and / or presentation of this data as part of the client application.
Demo for both options: https://jsfiddle.net/abhitalks/wuhnuv99/
Bottom line . Do not pass the code. Data transfer. Then the code should use this data.