假设我有JSF页面
<h:body>
<h:form id="formID" prependId="false">
<h:outputText id="randomID" value="#{randomNumber.random}"/>
<h:commandButton id="buttonID"
value="Random"
onclick="myArrayList(countries)" /> //just example
</h:form>
</h:body>
@ViewScoped
public class RandomNumber {
private int totalCountries;
private String data = "Afghanistan, Albania, Zimbabwe";
private List<String> countries;
public RandomNumber() {
countries = new ArrayList<String>();
StringTokenizer st = new StringTokenizer(data, ",");
while(st.hasMoreTokens()) {
countries.add(st.nextToken().trim());
}
totalCountries = countries.size();
} //end of constructor
} //end of class RandomNumber
.js文件
function myArrayList(countries) {
.....
}
查看用户点击按钮的时间,然后我想调用我传递ArrayList的Jquery函数。是否可以将当前的JSF变量与值传递给javascript或jQuery?
由于
修改 **的 _ __ _ __ _ __ _ __ _ __ _ __ _ __ _ __ _ __ _ __ _ < / EM> __ _ __ _ __ _ __ _ __ _ __ < EM> _ - *
<h:body>
<h:form id="formID" prependId="false">
<h:outputText id="countries" value="#{countries.countries}" style="display:none"/>
<h:inputHidden id="hiddenCountries" value="#{countries.countries}" />
<h:commandButton id="buttonID"
value="Random"
onclick="myArrayList()"/>
</h:form>
</h:body>
@ViewScoped
public class Countries {
private int totalCountries;
private String data = "Afghanistan, Albania, Zimbabwe";
private List<String> countries;
/** Creates a new instance of Countries */
public Countries() {
countries = new ArrayList<String>();
StringTokenizer st = new StringTokenizer(data, ",");
while(st.hasMoreTokens()) {
countries.add(st.nextToken().trim());
}
totalCountries = countries.size();
} //end of constructor
public List<String> getCountries() {
return countries;
}
public void setCountries(List<String> countries) {
this.countries = countries;
}
} //end of class Countries
function myArrayList() {
alert(jQuery('#countries').html());
alert(jQuery('#hiddenCountries').val()) //when using h:inputHidden
} //end of function myArrayList
答案 0 :(得分:1)
你可以做到
<h:inputHidden id="someID" value="#{randomNumber.data}/>
(别忘了将getter / setter添加到bean中的数据中)
更改h:commandButton
onclick="myArrayList()" // or onclick="myArrayList(#{SomeELExpressioGoesHere})"
将你的js功能改为
function myArrayList(inputParam) {
alert(jQuery('#someID').val());
var yourJSString = jQuery('#someID').val();
var myArray = yourJSString.split(','); //when string is Afghanistan,Albania,Zimbabwe (no spaces)
alert(myArray[inputParam]);
}
为了将你的js字符串转移到数组中,只需使用
var yourJSString = jQuery('#someID').val()
var myArray = yourJSString.split(','); //when string is Afghanistan,Albania,Zimbabwe (no spaces)
如果你不在表单中设置prependId = false,可能需要将someID
更改为其他id选择器...或者只是使用像
alert(('input[id$="someID"]').val());
修改强>
看看我的例子,你应该使用你的String数据变量而不是国家,因为你应该只将数据作为字符串而不是作为数组传递...在你将数据变量传递给js后你可以操作它使用简单的slpit js函数使其返回js中的数组...你得到转换错误设置值'[阿富汗,阿尔巴尼亚,津巴布韦]'为'null因为你试图将String设置为数组...可能是国家的getter隐式地将java数组转换为字符串,当你尝试将其提交回来(字符串到数组)时,你得到异常
为了从js设置回bean:
jQuery('#someID').val("Some new String goes here");
然后当您提交表单时......该值将被设置回服务器