0

Hello I want to append the parsed json(which I get from xmlhttprequest) to a html file.

Here is my code:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>alert solr response</title>
<script src="https://code.jquery.com/jquery-3.2.1.js">
</script>
<script>
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function () {
        if (xhr.readyState == XMLHttpRequest.DONE) {
            var json = JSON.parse(xhr.responseText);
            var data = json.facet_counts.facet_dates["dc.date.accessioned_dt"];
            delete data.gap;
            delete data.end;
            delete data.start;
            console.log(data)
            $("#test").append(data); //here is the problem, I could append xhr.Responsetext but this is not what I want
        }
    }
    xhr.open('GET', 'http://localhost:8080/solr/search/select?indent=on&rows=0&facet=true&facet.date=dc.date.accessioned_dt&facet.date.start=2016-01-01T00:00:00Z&facet.date.end=2017-12-01T00:00:00Z&facet.date.gap=%2B1MONTH&q=search.resourcetype:2&wt=json&indent=true', true);
    xhr.send(null);
</script>
</head>
<body>
<p id = "test">This is the json sample: <br></p>
</body>
</html>

I know there are lot of similar questions out there and possible duplicates, I am sorry I couldn't use them for my case(Being a noob and all) Thank you

1 Answers1

0

You can simplify this a bit if you are using jQuery, when you get your data you got to stringify the content using the third argument to get the indentation you want, since it's just plain text you would also have to append it to a <pre> tag or set the css at the p tag to: white-space: pre

$.get('https://httpbin.org/get').then(function(data) {
  delete data.gap;
  delete data.end;
  delete data.start;

  $("#test").text(JSON.stringify(data, null, 2));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre id="test"></pre>
Endless
  • 34,080
  • 13
  • 108
  • 131