javascriptjqueryhtmlxml

Not able to print <> brackets in XML output in html


So this is with regards to one of my previous questions, where in i wanted to replace "\n" with a "br" tag in HTML using JS. For the same page, if someone passes a XML or RPC query, i want to return an XML output.

A typical XML output looks like:

<racks>\n
<rack>\n
<rack-name>0</rack-name>\n
<chassis>\n
<serial-number>XYZ789</serial-number>\n
</chassis>\n
</rack>\n
</racks>\n
</diag>\n
</data>\n
</rpc-reply>\n

**I want to be able to print it in this way: (replacing \n with a br)

<racks>
<rack>
<rack-name>0</rack-name>
<chassis>
<serial-number>XYZ789</serial-number>
</chassis>
</rack>
</racks>
</diag>
</data>
</rpc-reply>

**

But i am only getting the plain text in the output, which is 0 and XYZ789 with so many \n's.

The JS:

$(function() {
  $('button').click(function() {
    $.ajax({
      url: '/runCommand_query',
      data: $('form').serialize(),
      type: 'POST',
      success: function(response) {
        response = response.replace(/(\n)/g, "<br>");
        console.log(response);
        $("#opt").html(response);
      },
      error: function(error) {
        console.log(error);
        $("#opt").val(error);
      }
    });
  });
});

Solution

  • You should use text() instead of html() like :

    $("#opt").text(response);
    

    Else the browser will interpret the code as HTML tags, and shows you just the text.

    Update

    var response = "<racks>\n<rack>\n<rack-name>0</rack-name>\n<chassis>\n<serial-number>XYZ789</serial-number>\n</chassis>\n</rack>\n</racks>\n</diag>\n</data>\n</rpc-reply>\n";
    
    $('#opt').text(response).wrap('<pre />');
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <div id="opt"></div>