A CDN I am switching to is charging per text/html content-type request (including AJAX requests), so I am converting as many ajax requests away from this content-type as possible.
Many of my ajax requests return HTML. What would be the easiest/best way to still convey this content but without the text/html content-type?
Two options I’m aware of, but wary of:
text/javascript
<div class="style1">smdrager's example content</div>
becomes
var content = '<div class="style1">smdrager\'s example content</div>';
Any single quotes will have to be escaped. Is there any unforseen problems with passing content in a simple variable?
application/json
<div class="style1">smdrager's example content</div>
becomes
{"content" : "<div class=\"style1\">smdrager's example content</div>"}
Any double quotes, which are common will have to be escaped. I feel like this would be safer than the variable approach, but I will have to do more work to escape every double quote than single as with the simple variable approach.
EDIT:
Thought of a third option which is easier than the other two. Anyone have any better?
commented javascript
I thought of this:
<div class="style1">smdrager's example content</div>
becomes
/*<div class="style1">smdrager's example content</div>*/
This works without any escaping. The only thing to change in the content is to remove any other javascript block comments, which really shouldn’t be in ajax’ed content anyway.
Is there any approach or content-type which can get me out of having to escape special characters without risking browsers having trouble with the content-type?
Thanks
Me: Can’t you just change the content type, but leave the content the same?
Asker: Wouldn’t that cause errors? Like as text/javascript it could cause javascript errors couldn’t it?
Me: Who would complain? javascript isn’t executed by itself just by it’s existance as “text/javascript”. Javascript is executed when it’s in a script tag on a page, or actually explicitely executing from some other javascript that has started. So I reckon if you just ask for the data, regardless of the mimetype, it won’t be parsed or executed unless you pass it through something that tries to do that.
Asker: David, you are correct. I am converting them to text/plaintext now just to be safe. So far, it seems no other changes are needed which makes this the simplest way to do it.