Search code examples
javascriptjavajqueryhtmlhttpserver

Why am I getting the html tags from jQuery and HttpHandler?


I have the following code :

 <script>
 $(document).on('click','#Save',function()
 {
   $.get('My_App?New_Info='+$('button[id^=\"Current_\"]').text(),function(responseText)
   {
     $('#Page_div').text(responseText);
   });
 });
 </script>

The html looks like this :

<div id=Page_div>
      <Table Border=1>
        <Tr>
          <Td><button id=Current_1 type=button></button></Td>
          <Td><button id=Current_2 type=button></button></Td>
          <Td><button id=Current_3 type=button></button></Td>
          <Td><button id=Current_4 type=button></button></Td>
          <Td><button id=Current_5 type=button></button></Td>
          <Td><button id=Current_6 type=button></button></Td>
          <Td><button id=Save type=button>Save</button></Td>
        </Tr>
      </Table>
</div>

And the HttpHandler code looks like this :

  public void handle(HttpExchange exchange)
  {
    OutputStream responseBody=exchange.getResponseBody();
    String requestMethod=exchange.getRequestMethod(),requestPath=exchange.getRequestURI().getPath(),title="ABC",
             New_Info,responseString="<Html>\n<Head>\n  <Title>"+title+"</Title>\n</Head>\n<Body BgColor=#FDF5E6>\n<Center>\n"+Get_jQuery()+"\n\n";
    LinkedHashMap<String,String> params=queryToMap(exchange.getRequestURI().getRawQuery());
    File file;

    try
    {
      New_Info=(params.get("New_Info")==null?null:URLDecoder.decode(params.get("New_Info"),"utf-8"));

      if (New_Info!=null)                                                                    // After Save button is clicked, save new user info
      {
        Headers responseHeaders=exchange.getResponseHeaders();
        responseHeaders.set("Content-Type","text/html;charset=utf-8");
        exchange.sendResponseHeaders(200,0);
        responseString="<P><H2>Info [ "+New_Info+" ] saved.</H2>";
        responseBody.write(responseString.getBytes());
      }
...
}

All is well, except one thing, the buttons are replaced with new text from HttpHandler, which is the string : "<P><H2>Info [ xx ] saved.</H2>"

But I expect it to be in big fonts and the text on the screen should be : "Info [ xx ] saved." rather than the RAW un-rendered version showing user the html tags, why ? I also tried :

responseHeaders.set("Content-Type","text/plain");

No difference, I also tried to put <html> ... </Html> around it, still didn't work, what's the correct way to fix it ?


Solution

  • text() means "Treat the content as plain text".

    If you want to treat it as HTML source code then use html() instead.