Kris Schouw
Kris Schouw

Reputation: 352

Is it Better Practice to Inject HTML Through a Server or Through JavaScript?

My current project has me accessing a database quite frequently. To do so, I make calls to my Java Servlet through jQuery Get and Post calls. I was wondering if it was better practice to build any HTML using the data I gather from the database within the servlet before I ship it back to the jQuery or if I should do the HTML injecting with JavaScript alone? For example, let's say I have a database table with a user ID and a username. If I wanted to create a select box off this table, which would be the better way? Or is there even a better way? Would it be better to just try send the rawest form of the data retrieved from the database from the servlet to the JavaScript, allowing it to handle all of the HTML formatting?

Method 1 (Java)

Given the Following HTML/JavaScript

<html>
    <head>
        <script type="text/javascript" src="scripts/jquery.min.js"></script>
        <script type="text/javascript">
            $(document).ready(function() {
                $.get("servlet?cmd=getUsers", function(data) {
                    $("#select").html(data);
                }, "html");
            });
        </script>
    </head>
    <body>
        <div id="select"></div>
    </body>
</html>

Using The Following Servlet

PrintWriter writer = response.getWriter();
response.setContentType("text/html");

writer.println("<select id='userSelect' name='user'>");
while(resultSet.next()) {
    String userId = resultSet.getString("ixUser");
    String userName = resultSet.getString("sName");

    writer.println("<option value='" + userId + "'>" + userName + "</option>");
}
writer.println("</select>");

Method 2 (JavaScript)

Given the Following HTML/JavaScript

<html>
    <head>
        <script type="text/javascript" src="scripts/jquery.min.js"></script>
        <script type="text/javascript">
            $(document).ready(function() {
                $.get("servlet?cmd=getUsers", function(data) {
                    $("#select").html("<select id='userSelect' name='user'>");
                    $(data).find("user").each(function() {
                        var id = $(this).find("id").text();
                        var name = $(this).find("name").text();

                        $("#userSelect").append("<option value='" + id + "'>" + name + "</option>");
                    });
                    $("#select").append("</select>");
                }, "xml");
            });
        </script>
    </head>
    <body>
        <div id="select"></div>
    </body>
</html>

Using the Following Servlet

PrintWriter writer = response.getWriter();
response.setContentType("text/xml");

writer.println("<xml>");
while(resultSet.next()) {
    String userId = resultSet.getString("ixUser");
    String userName = resultSet.getString("sName");

    writer.println("<user>");
    writer.println("<id>" + userid + "</id>");
    writer.println("<name>" + userName + "</name>");
    writer.println("</user>");
}
writer.println("</xml>");

Upvotes: 5

Views: 1520

Answers (5)

roselan
roselan

Reputation: 3775

method 1, as you are not comfortable enough with method 2.

a few words on method 2. choose between string concatenation, or object building.

var html = '<select...
...
html .= '</select>';
$("#select").append(html);

or

var $sel = $('<select>').attr('id', 'userSelect').attr('name', 'user').

as you see, $('<tag>') syntax creates a new dom element.

Moreover, return a json object instead of xml if you can. They are more easy to work with in javascript. So you can do

for (i in data) {
   $('<option>').text(data[i].name).val(data[i].id).appendTo($sel);
}
$("#select").append($sel);

And then, there is method3: templating...

Upvotes: 0

Larry K
Larry K

Reputation: 49104

These days the cool kids do MVC on the browser. -- Your method 2, but a more sophisticated client-side stack.

In other words, your server exports an api that provides data, not html.

Then, on the browser, your JS app has separate Model, View and Controller code. See the Backbone project for the Model and Controller layer, Mustache for the View/Template layer. An article. Another post.

Upvotes: 0

Brian
Brian

Reputation: 4984

I'd suggest returning only the data in a lightweight manner such as JSON.

My reasons:

  • Bandwidth
  • Smaller data to be cached when performance concerns come into play
  • Flexibility. If you wanted to expose this data to another part of your application or a mobile device?

There are several other methods but in my mind this is a much more organized approach. Let the client deal with the markup processing.

I would suggest jQote2 as an awesome client side templating tool. (It's just awesome!)

Upvotes: 0

Ryan Gross
Ryan Gross

Reputation: 6515

It seems that the world is moving towards your second approach. There are several reasons for this:

  1. Your users will perceive that your application is more responsive than it actually is because the page will be loaded in parts, so there is always progress being made (or at least a progress indicator if there is something that takes a long time to load).
  2. You can re-use the data services for additional clients other than your website (think native mobile apps).
  3. The data format is almost always more compressed than the html that is generated, so you send less data over the wire. I would actually recommend json over xml for this reason.
  4. The javascript engines in most browsers are much more efficient than they were a few years ago. This allows you to offload some of the more complex page layout logic from your server, making your application more scalable.
  5. It will be easier to test that the data returned is correct without having to wade through the formatting html to access it.

Upvotes: 0

Demian Brecht
Demian Brecht

Reputation: 21368

I'd opt for sending raw (well, JSON) data to the client and have Javascript take care of the templating. Why?

Separation of concerns: Your server code shouldn't be aware of the presentation logic.

Less bandwidth: If you can save a few k/request (at least), why not?

Upvotes: 3

Related Questions