ajaxjsonprototypejsscriptaculous

How To Elegantly Handle JSON Objects in Responses From Ajax Requests?


I'm really new to using JSON to handle my Ajax Request and Response cycle. I've previously used just plain old parameters passed as POST data and I've rendered straight HTML in the response which was then placed into the DOM. As I've looked at various examples and read through various tutorials, it seems like a fairly common practice to simply build a string from the JSON object mixed with HTML that's been hard coded into the string and then assign the string as innerHTML to some element.

A common example looks something like this:

var jo = eval(req.responseText);

var strTxt = '<span>' + jo.f_name + ' ' + jo.l_name + '</span><br/>' + 'Your Age Is: ' + jo.age + '<br/>'; 

$('myDiv').innerHTML = strTxt;

Is there a more elegant (or correct) way of handling the JSON response so that I'm not hard coding HTML in the javascript? Or is this pretty much how people do it?

P.S. Links to tutorials or other sources are appreciated.


Solution

  • I steer away from writing a lot of HTML within JavaScript strings. I prefer separation of structure from data manipulation. The better alternative is to place that code in the page, load the values based off the ID's, and show/hide it if necessary:

    <div id="codeBlock" style="visible=false;">
        <span id="val1"></span>
        <br/>
        <span id="val2"></span>
        <br/>
    </div>
    ............
    <script>
        var jo = eval(req.responseText);
        $('val1').innerHTML = jo.f_name + ' ' + jo.l_name;
        $('val2').innerHTML = 'Your Age Is: ' + jo.age;
        $('codeBlock').show();
    </script>
    

    That might not be exactly what you want to do but you get the idea.