JSF bean属性未在外部JavaScript文件中评估

per*_*ssf 1 javascript jsf el java-ee

如果我想从JavaScript中评估一个JSF bean属性,我发现如果JavaScript代码片段在xhtml文件中,它可以工作,但是当JavaScript代码片段在一个单独的js文件中时,它不起作用.

所以,这有效:

的index.xhtml

...
<h:body>
    <script type="text/javascript" src="resources/Javascript/jquery/jquery-1.7.2.js" />
    <script type="text/javascript" >
        $(document).ready(function() {
            alert('#{myBean.myProperty}');
        });
    </script>        
</h:body>
Run Code Online (Sandbox Code Playgroud)

但这不会评估ManagedBean的属性:

的index.xhtml

...
<h:body>
    <script type="text/javascript" src="resources/Javascript/jquery/jquery-1.7.2.js" />
    <script type="text/javascript" src="resources/Javascript/MyJS.js" />
</h:body>
Run Code Online (Sandbox Code Playgroud)

MyJS.js

$(document).ready(function() {
    alert('#{myBean.myProperty}');
});
Run Code Online (Sandbox Code Playgroud)

在第二种情况下,警告框包含未评估的字符串 #{myBean.myProperty}

如何从外部js文件中使其工作?

小智 5

另一种解决方案是将*.js文件更改为*.xhtml并将其包含在"<ui:include ... />"中.为避免解析器抱怨在*.xhtml文件中使用&,<和>,请用CDATA标记将其包围.这样做的缺点是如果在其他页面中使用*.js文件,浏览器将无法缓存它.

MyJS.xhtml(从MyJS.js更改)

<xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:ui="http://java.sun.com/jsf/facelets">

<h:body>
<ui:composition>

<script type="text/javascript">
//<![CDATA[
  ...your JavaScript code here...
//]]>
</script>

</ui:composition>
</h:body>
</html>
Run Code Online (Sandbox Code Playgroud)

index.xhtml文件中,执行以下操作:

<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:ui="http://java.sun.com/jsf/facelets">
  ...
<ui:include src="MyJS.xhtml" />
Run Code Online (Sandbox Code Playgroud)