How to elegantly handle JSON objects in responses from Ajax requests?

I am really new to using JSON to handle the Ajax Request and Response loop. I previously used only the old parameters passed as POST data, and I displayed direct HTML in the response, which was then placed in the DOM. As I looked at various examples and read various tutorials, it seems pretty common practice to just build a string from a JSON object mixed with HTML that was hard-coded into a string, and then assign the string as innerHTML to some element.

A general 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 to handle a JSON response so that I don't have hardcoded HTML in javascript? Or is it pretty much how people do it?

PS Links to textbooks or other sources are welcome.

+4
source share
4 answers

I am avoiding writing a lot of HTML in JavaScript strings. I prefer separation of structure from data manipulation. The best alternative is to place this code on the page, load the values ​​based on identifiers, 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> 

This may not be exactly what you want to do, but you get the idea.

+1
source

You can create elements in the DOM with javascript, and not just drop them in the innerHtml DIV, something like the following (untested):

 var mySpan = document.createElement("span"); var spanContent = document.createTextNode(jo.f_name + ' ' + jo.l_name); mySpan.appendChild(spanContent); var myBr = document.createElement("br"); mySpan.appendChild(myBr); var otherSpanContent = document.createTextNode('Your Age Is: ' + jo.age); mySpan.appendChild(otherSpanContent); mySpan.appendChild(myBr); $('myDiv').appendChild(mySpan); 
+2
source

You can check the template engine, for example PURE - at first it’s a little difficult to get there, but it supports many basic javascript structures (and DOMAssistant, which is good) and separates html from data.

+2
source

Objects created from JSON are standard Javascript objects, so you can easily use jQuery selectors to create or access DOM elements and insert content from your JSON objects.

eg.

 // Create a new span element and set its text var personSpan=$("<span>").text(jo.f_name + ' ' + jo.l_name); // Append the span to the existing myDiv element $("myDiv").append(personSpan); // Create a new div element (better then br) and set its text var personDiv=$("<div>").text("Your Age Is: " + jo.age); // Append the new div to the existing myDiv element $("myDiv").append(personDiv); 
+1
source

All Articles