Returning AJAX HTML response without CSS / JS intervention
I have an AJAX call to the server that will return an HTML response. This HTML response will include HTML, CSS and JS. I would like to include this answer on my current page so that the user can view the answer. I tried the following, but the CSS from the answer applies to my current page. Is there a way to prevent CSS from being used for my current page?
Please note that I have no control over the CSS returned by the server. The server may return a CSS, which is designed for all types of elements p { color:red }
: (
$.ajax ({
type: TYPE,
contentType: CONTENT_TYPE,
url: URL,
headers: {
firstName: firstName,
lastName: lastName
}
})
.done( function(msg) {
$('#response').html(msg);
})
<div id="response"></div>
source to share
I expanded Braks idea of using iframe, creating an iframe, and replacing it with the content on the jQuery:
$('<iframe id="someId"/>').appendTo('#someDiv').contents().find('body').append(response);
.
You can learn more about this at: Create an <iframe> element and add html content to it using jQuery
source to share
Tagging
Assuming the CSS answer is in style:
var _html = $('<div>' + msg + '</div>'); // Parses response string
_html.find('style').remove(); // Selects and removes style tags
msg = _html.html(); // Makes it a string again
This will strip all tags <style>
to a line
<h / "> You can also remove all attributes style
:
var _html = $('<div>' + msg + '</div>');
_html.find('[style]').removeAttr('style');
msg = _html.html();
<h / "> If their <link>
var _html = $('<div>' + msg + '</div>');
_html.find('link[rel=stylesheet]').remove();
msg = _html.html();
You can always combine them to get the desired result.
<h / ">
floating frames
You can use iframe
to get the result:
$('#response').attr('src', 'data:text/html;charset=utf-8,' + encodeURIComponent(msg));
<h / ">
Cut <style>
and <link>
example
.done(function(msg) {
var _html = $('<div>' + msg + '</div>');
_html.find('style, link[rel=stylesheet]').remove();
$('#response').html(_html.html());
})
source to share