JSF 2.2 CDATA is escaped

一世执手 提交于 2019-12-07 19:21:28

问题


I have found some weird behaviour after upgrading to Mojarra 2.2.3. The following Javascript declaration gets mangled:

In the .xhtml file:

<script type="text/javascript">
<!-- /* <![CDATA[ */
    $(document).ready(function() {                                                                             
        if ($('#some_identifier').size() > 0) 
        ...
/* ]]> */-->
</script>

This is mangled into the following nonsense:

<script type="text/javascript">
<!-- /* &lt;![CDATA[ */
    $(document).ready(function() {
        if ($('#some_identifier').size() &gt; 0)
        ...
/* ]]&gt; */-->
</script>

This breaks all javascript code embedded in .xhtml files. I verified that this does not happen with the versions we used previously (2.0.x), so I must assume it's got something to do with the new Mojarra version. Any ideas on how to fix this or work around it?


回答1:


This CDATA syntax is completely invalid. It's not clear where you got this from and why you thought it would be valid. Perhaps you confused it with CDATA syntax for CSS code. In any case, for proper CDATA syntax in JS code, carefully read this Mozilla Developer Network article: Writing JavaScript for XHTML.

The valid (modern) syntax is:

<script type="text/javascript">
  <![CDATA[
    $(document).ready(function() {                                                                             
      if ($('#some_identifier').size() > 0) 
        ...
  ]]>
</script>

If you really, really need to support old browsers which no one on the world uses, then use the following syntax which should work in those browsers which doesn't natively support JavaScript and therefore are incapable of parsing <script> elements (wonder yourself, would your JSF application, rich of JavaScript, still work on those webbrowsers? would it really be useful to escape JS for them as well?)

<script type="text/javascript">
  <!--//--><![CDATA[//><!--
    $(document).ready(function() {                                                                             
      if ($('#some_identifier').size() > 0) 
        ...
  //--><!]]>
</script>

By the way, much better is to put that JS code in its own .js file.

See also:

  • Error parsing XHTML: The content of elements must consist of well-formed character data or markup


来源:https://stackoverflow.com/questions/18849528/jsf-2-2-cdata-is-escaped

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!