I tried to load entire page by ajax (doctype and html tags removed). And then
document.documentElement.innerHTML=xmlhttp.responseText;
But Google Chrome says: An invalid or illegal string was specified.
The same error if I do:
document.documentElement.innerHTML='<head><meta></head><body></body>';
But it's ok with this string:
document.documentElement.innerHTML='<head></head><body></body>';
Try this:
document.write(xmlhttp.responseText);
Of course you'll need to include the html tag and doctype.
Related
The question is pretty self explanatory. What I want to do is changing the value of a textarea with jQuery. What I do is:
$( '#embedcode' ).val( "<script id='embed_1' src='/javascripts/test.js' type='text/javascript'></script>" );
What is the right way to do that. I keep getting an error :
Uncaught SyntaxError: Unexpected identifier
How to make the that I want to add as a string not a script.
Here you go:
Make your String like this :
$('#embedcode').val("<script id='embed_1' src='\/javascripts\/test.js' type='text\/javascript'><\/script>");
Check out this JsFiddle i made for you:
http://jsfiddle.net/KB9Qn/14/
You need to escape the "<" and ">".
$('#embedcode').val("\<script id='embed_1' src='/javascripts/test.js' type='text/javascript'\>\</script\>");
Demo
Your code seems to work perfectly. Here's the live demo: Click here
You need to check the line number where you are getting that error.
edit: I just had the thought. If your html markup has an error (maybe an unclosed textarea) the script can be evaluated as a script tag rather than text. Check for that. Here is a live example of an html error that will cause your problem. Click here.
Update: I believe I know exactly what the real issue is. The other posts are recommending that you escape the '<' and '>', but that should only be necessary if this javascript you are using is actually in an html file (or html generated by the server) rather than in a js file where it belongs. In the js file, it will naturally be a string as you have written it, but the html file sees it as markup even though it isn't intended to be. This is an example of why you should follow the best practices and keep javascript in a js file.
escape the < and > in the string with \
I'm working on a lightbox script and running into a problem using a custom data-lightbox attribute. What I'm trying to do is allow for the data-lightbox attribute settings to be added dynamically to the page - on an image.
Here's my image:
<a href="largeimage.png" data-lightbox='{"setting":"value","setting":"value"}'>
<img src="thumbnail.png" />
</a>
Here's the part of the script that I'm using to inject the settings:
$('#testthumbnail').find('a').attr('data-lightbox',settings);
Settings is just a string, that is getting dumped into the attribute. When run, I don't receive any errors, and the settings are all injected to the data-lightbox attribute correctly. The settings aren't taking effect in the plugin though for 1 reason - somewhere along the lines the html that gets output to the page looks like this:
<a href="largeimage.png" data-lightbox="{"setting":value"}"> ...
The surrounding ' ' on the data-lightbox attribute are converted to " " - which won't work in my situation. Does anyone have any idea why the apostrophes are converted to quotes and how I can possibly get around this?
Thanks!
UPDATE:
I have the settings variable available both as a properly formatted JSON string as well as an object. I've tried using both the Object and the string inside the data-lightbox attribute, but am running into the same problem. The browser is converting my ' 's to " "s which is causing JSON errors.
Your quotes are wrong. HTML attributes need to use double quotes. So you need to use the single ones on the JSON value. The browser output you see is the browser trying to do the best it can to correct the html.
I've just run into a pathological case with HTML parsing. I've always thought that a <script> tag would run until the first closing </script> tag. But it turns out this is not always the case.
This is valid:
<script><!--
alert('<script></script>');
--></script>
And even this is valid:
<script><!--
alert('<script></script>');
</script>
But this is not:
<script><!--
alert('</script>');
--></script>
And neither is this:
<script>
alert('<script></script>');
</script>
This behavior is consistent in Firefox and Chrome. So, as hard as it is to believe, browsers seem to accept an open+close script tag inside an html comment inside a script tag. So the question is how do browser really parse script tags?
This matters because the HTML parsing library I'm using, Nokogiri, assumed the obvious (but incorrect) until-the-first-closing-tag rule and did not handle this edge case. I imagine most other libraries would not handle it either.
After poring over the links given by Tim and Jukka I came to the following answer:
after the opening <script> tag, the parser goes to data1 state
if <!-- is encountered while in data1 state, switch to data2 state
if --> is encountered while in any state, switch to data1 state
if <script[\s/>] is encountered while in data2 state, switch to data3 state
if </script[\s/>] is encountered while in data3 state, switch to data2 state
if </script[\s/>] is encountered while in any other state, stop parsing
All the examples are invalid as per the HTML 4.01 specification: the content of script is declared as CDATA, and the description of CDATA says:
“Although the STYLE and SCRIPT elements use CDATA for their data model, for these elements, CDATA must be handled differently by user agents. Markup and entities must be treated as raw text and passed to the application as is. The first occurrence of the character sequence "</" (end-tag open delimiter) is treated as terminating the end of the element's content. In valid documents, this would be the end tag for the element.”
As you have observed, browsers might not enforce this rule but instead recognize pairs of start and end tags, in some situations. From the spec perspective, this is handling of invalid documents, i.e. error processing. It is not clear what exactly they are doing here and why. It seems to depend on the presence of <!--, which should not have any effect on HTML 4.01 parsing (it is not a comment opener in CDATA content).
In XHTML, partly different rules apply, because in XHTML, <!-- opens a comment within the content of a script element.
As an aside, all the examples are invalid HTML 4.01 and invalid XHTML due to the lack of the type attribute in script. The attribute is not needed (browsers default to treating the content as JavaScript), but it’s required by those specs.
In HTML5, other rules apply. They are rather complicated, and they are supposed to describe browser behavior. In addition to imposing restrictions on content (forbidding e.g. <!-- without matching -->), HTML5 also specifies parsing rules.
Content of tags is still HTML, unless you mark it as not being HTML. In HTML, <word> is taken to be a tag, < needs to be written as < to avoid this behaviour. Alternately, you want to make the contents of <script> a text node; use this formula:
<script type="text/javascript">
//<![CDATA[
// your code, with < and & and "", woohoo!
//]]>
</script>
<![CDATA[ ... ]]> delineates a part of the document as pure text, without markup. Slashes are there so JavaScript wouldn't get confused; the first set of slashes is outside CDATA, but they're HTML-safe, so there's no problem.
EDIT: Just realised the question is about parsing, not writing HTML. Oops.
Hypothetically, if the tags are parsed first and the comments are parsed later, the HTML parser would give you those results.
(I don't mean this is necessarily the case, just a possible explanation only.)
1st case
<script><!--
alert('<script></script>');
--></script>
There is a set of <script></script> inside another <script></script>. The parser may ignore the name of the tags first and just checks for proper opening and closing of those tags. Then it parse the comments.
<script><!--
--></script>
So this is valid.
2nd case
<script><!--
alert('<script></script>');
</script>
There is a set of <script></script> inside another <script></script>. Then it parse the comments.
<script><!--
The comment extends all the way to the end of the document. This is not strictly valid, but the browser handles it correctly.
3rd case
<script><!--
alert('</script>');
--></script>
There is a single closing tag inside the set of <script></script>. It is invalidated before it parse out the </script> as comments.
4th case
<script>
alert('<script></script>');
</script>
There is a set of <script></script> inside another <script></script>, and there are no comments. The first pass is valid but then it really looks into the tags to see what they are. It may not accept a pair of <script> tags inside another one so it invalidates the case.
I use the following PHP code to generate some JS and echo it in my page
$var_x = $var_x . "var_array[$var_count] = '<div class=\"var_div\"></div>'; ";
However, when I try to validate it with the W3C validator, I get the following error.
'document type does not allow element "div" here'
The error highlights the > at the end of the tag
What could be the problem?
Use the XHTML CDATA section to denote areas where you may be working with HTML. This will let the validator know that it needs to ignore the contents and not try to parse it.
Yes, this will error out, because you are trying to build html document element inside javascript.
If you echo php variable $var_x in the javascript, it will write your string into document and your string contains document element and when HTML try to parse your html and javascript it will error out.
My script function is defined inside a JSF2 form on a XHTML page and the following part of the code causes a problem:
<script type="text/javascript">
function myFunction(){
var checkboxes = document.getElementsByName('mycheckboxes');
if(checkboxes.length > 0){
for (var i=0; i<checkboxes.length; i++){
var checkbox = checkboxes[i];
}
}
}
</script>
When trying to access the page in FireFox 8 it prints the exception:
Element type "checkboxes.length" must be followed by either attribute specifications, ">" or "/>"
what does this error mean?
Another question: is the script is executed before the pages is rendered? Because my checkboxes is loaded in the page during render phase of page (using JSF <ui:repeat>), so my guess is that I must make a condition to execute the code when the variable checkboxes is not null, am I right?
It looks like you are using XHTML and embedding scripts in the page.
XML doesn't have intrinsic CDATA sections, so < means "start of tag" even inside a script element.
If you were using real XHTML then you could represent it as <, but then you couldn't serve the document as text/html.
Instead you can wrap the script content with an explicit CDATA section as described in the specification while also taking care to follow the relevant text/html compatibility guidelines.
You would probably be better off keeping your script in an external file and loading it with <script src="..."></script>.
For that matter, you are likely to be better off using HTML instead of writing XHTML and then jumping through hoops to make it work in browsers that expect HTML.
If you write this script directly in the JSF source - you have to escape symbols like >, <, & etc. with >, & ...
Another way is to use CDATA section:
<script language="javascript">//<![CDATA[
/* here your script */
//]]>
</script>
See also:
http://www.w3schools.com/xml/xml_cdata.asp
What characters do I need to escape in XML documents?
"This error comes from not closing an attribute tag".
http://www.judahfrangipane.com/blog/2006/12/31/element-type-must-be-followed-by-either-attribute-specifications/