开发者

Fix a warning thrown by HTML Validator

I have some JavaScript code in my php website.

This code uses jQuery, and builds a < 开发者_开发知识库select > menu using ajax calls.

Here is the code

sel.append('<option value="' + data[i].id + '">' + data[i].nombre + '</option>');

And this gives me the following warning

line 240 column 82 - Warning: '<' + '/' + letter not allowed here

Does anyone know how can I fix this warning, so my html validates? Thanks


The issue is that any </ sequence — known as ETAGO — ends a CDATA element such as a <script>. You can get away with </ in browsers but not </script.

The simplest workaround is to break up the </ sequence with a backslash-escape:

sel.append('<option value="' + data[i].id + '">' + data[i].nombre + '<\/option>');

However this line still has problems, because you aren't HTML-escaping your id and nombre values. If they may contain <, & or ", you've just built yourself a client-side XSS vulnerability!

So either HTML-escape your text values before putting them into strings, or, perhaps simpler, just use the standard DOM:

sel.append(new Option(data[i].nombre, data[i].id));


Put the javascript in an external file.


If you are writing javascript in the html/xhtml page, you can enclose the javascript in CDATA

<script type="text/javascript">
/* <![CDATA[ */
console.log("..js code here..");
/* ]]> */
</script> 


To include code which isn't encoded as XML in an XHTML document (and I'm guessing that's what you're trying to do) you need to do something like the following:

<script type="text/javascript">
//<![CDATA[

alert("<This is now valid XHTML>");

//]]>
</script>


Put <!-- and --> around your code.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜