views:

94

answers:

2

I make the following AJAX pull with JQuery using JSON to an ASP.net Web Service:

$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "TestWebService.asmx/Foo",
data: "{}",
dataType: "json",
success: function(msg) {
    $("#justpre").html(msg.d);
    $("#precode").html(msg.d);
} } );

The TestWebService implements a very simple WebMethod Foo() that returns the following:

[WebMethod]
public string Foo() {
    return "multi" + Environment.NewLine + "line" + Environment.NewLine + "comment";
}

Finally, I display the result

<pre id="justpre"></pre>

<pre><code id="precode"></code></pre>

Firefox and Chrome display the returned value as a multi-line comment just fine. IE7, however, renders it as a single-line with no line breaks.

FF, Chrome:
multi
line
comment

IE7:
multi line comment

How can I fix this?

+1  A: 

IE has some known issues with manipulating text upon inserting it into a pre tag.

Here is some more information: http://www.quirksmode.org/bugreports/archives/2004/11/innerhtml_and_t.html

Your best bet may be to sniff for IE and replace the \n characters with <br /> elements OR sniff for IE and use the IE only innerText, instead of innerHTML. Something like

document.createTextNode("multi\nline\ncomment");

might also do the trick in a cross browser way.

Alex Sexton
A: 

Instead of using the "pre" tag, try using CSS on the parent tag

.theParentTagOfPre {
   white-space: pre-wrap;
}

More Info on white-space

Mike