Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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."

    }]
like image 957
David Avatar asked Oct 03 '17 06:10

David


2 Answers

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;
}
like image 186
guest271314 Avatar answered Oct 26 '22 09:10

guest271314


Once you have your element, you can use innerHTML to put stuff inside of it. So supposing you already parsed your json and the data you want is inside the jsonc variable you can do

para.innerHTML = jsonc[0].VALUE;
like image 25
Federico klez Culloca Avatar answered Oct 26 '22 10:10

Federico klez Culloca