1

We have a JavaServlet running which provides us with needed data. The problem is the way Jquery interprets this data.

Information is sent through the response writer. (Eg: messages)

protected void doPost(HttpServletRequest request,
    HttpServletResponse response)
        throws ServletException {

    String body = "";
    for (Message msg : messages) {
        body += "<div class=\"Message\" id=\"" + msg.getId() + "\">"
            + *inner information*
            + "</div>";
    }
    response.getWriter().write(body);
}

The information is gotten through Ajax requests

$.ajax({
    type: 'POST',
    url: 'message.jsp',
    data: { *Needed data* },
    success: function(data) {
        $('#element').append(data);
    }
});

This sometimes works and sometimes it does not. So we checked the console in chrome and let the code stop at the append line. When multiple messages are sent the 'data' in the success function is interpreted as a big string,

"<div class="message" id="153" onclick="loadFullMessage(153)"></div>
<div class="message" id="154" onclick="loadFullMessage(154)"></div>
<div class="message" id="155" onclick="loadFullMessage(155)"></div>
<div class="message" id="156" onclick="loadFullMessage(156)"></div>
"

but when only 1 message/div is send it is interpreted as a '#document' object.

#document
    <div class=​"message" id=​"174" onclick=​"loadFullMessage(174)​">​…​</div>​

The message is available as can be seen in chrome console, but when appending the following error is encountered 'Uncaught Error: HIERARCHY_REQUEST_ERR: DOM Exception 3'.

How can the data just always be interpreted as a string and not change into the document object?

Peter Raeves
  • 516
  • 1
  • 4
  • 17

2 Answers2

3

@boblail is right - changing dataType to ajax will make it. However, you sometimes use third party libraries that you are not going to modify. It's JQuery UI in my case.

Sending Content-Type: application/xhtml+xml causes JQuery to build a DOM Document out of the response. Set your Content-Type to text/html and you are fine.

Nowaker
  • 12,154
  • 4
  • 56
  • 62
1

I just solved a very similar issue by adding dataType to the ajax call:

$.ajax({
  type: 'POST',
  url: 'message.jsp',
  data: { *Needed data* },
  success: function(data) {
    $('#element').append(data);
  }
});

See also these two StackOverflow answers:

Community
  • 1
  • 1
boblail
  • 11
  • 1