David David - 1 year ago 140
HTML Question

How to add json value in P tag in Javascript

Onclick of some tab I am creating para tag and on that I want to add some text. How to add those value dynamically.

Here is what I am trying.

Onclick of tab I am calling this method.

SomeMethod = function(){
var para = document.createElement("P");
para.setAttribute("id", "myUL");


function getData(callback) {
debugger;
var httpRequest = new XMLHttpRequest();
httpRequest.open('GET', "../resource/para.json", true);
httpRequest.onreadystatechange = function() {
if (httpRequest.readyState === XMLHttpRequest.DONE && httpRequest.status === 200) {
callback(httpRequest.responseText);
}
};
httpRequest.send();
}

getData(function(data) {
var jsonc = JSON.parse(data);
debugger;
document.getElementById('myUL').innerHTML = jsonc[0].VALUE;
});
}


My JSON data is

[{
"ID" : 0,
"VALUE" : "My 10000 Character text."

}]

Answer Source

You can define a second parameter at getData function, pass para as second parameter, set .textContent of para to result of JSON.stringify() with jsonc passed as parameter or jsonc[0].VALUE, pass para to .appendChild() to append the element to the document

JavaScript

para.className = "json";

// pass `para` to `getData()` call
callback(httpRequest.responseText, para);

// `element`: `para` passed at `callback`
getData(function(data, element) {
    var jsonc = JSON.parse(data);
    element.textContent = JSON.stringify(jsonc, null, 4); // or `jsonc[0].VALUE`
    document.body.appendChild(element);
    debugger;
});

CSS

p.json {
  white-space: pre;
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download