How do I prevent the JQuery.html () method from changing?
I am creating a website where I want to display some Java code as well. I am using AJAX request to get HTML content from server. The content is then inserted into a separate div with the content id.
To insert HTML content that also contains Java code, I use the JQuery .html(htmlString)
. However, the Java code changes as follows:
When using generics in Java, JQuery treats it as a tag! For whatever reason, the .html method suddenly changes all text between <
and >
to lowercase.
How can you avoid this behavior? Is there any parameter I can set to stop it? It doesn't even have to do it, because first of all it's unexpected, and secondly, it doesn't matter if the characters are lower or upper case, browsers will still understand, probably because they envelop themselves at some point inside.
EDIT # 1:
.empty () and then .append () results in the same behavior.
EDIT # 2:
The problem is that inside the result AJAX response
there is not only Java code
, but also true HTML content
, which will also be escaped if I use escape()
.
Edit # 3:
One of the comments mentioned, maybe I should refactor the AJAX response to keep the text and HTML content separate from each other. This sounds like a good idea in general, and maybe I'll go with that. I wonder, however, if there is any method for setting HTML content that doesn't make the content go with unwanted changes.
source to share
Javascript has no HTML entity transform function, but you can roll your own. Example:
if(typeof escapeHtmlEntities == 'undefined') {
escapeHtmlEntities = function (text) {
return text.replace(/[\u00A0-\u2666<>\&]/g, function(c) {
return '&' +
(escapeHtmlEntities.entityTable[c.charCodeAt(0)] || '#'+c.charCodeAt(0)) + ';';
});
};
// all HTML4 entities as defined here: http://www.w3.org/TR/html4/sgml/entities.html
escapeHtmlEntities.entityTable = {
34 : 'quot',
38 : 'amp',
39 : 'apos',
60 : 'lt',
62 : 'gt',
};
}
Then call
.html(escapeHtmlEntities(javaBlock));
source to share