Well, JSF does not allow calling arbitrary Java code using JavaScript.
It only allows you to trigger requests that call the bean methods it would call if a JSF component had triggered it (say, a commandButton
were clicked, for example), using the jsf.ajax
Javascript object. Check out the API here.
This API is very tight to the View code, it triggers a request and also the updates to parts of the view.
For example, here is a commandButton
very similar to yours, but using vanilla JavaScript to trigger the AJAX instead of the f:ajax
tag and with a small bit of additional JS code:
<h:commandButton value="Execute Demo" id="executeDemo"
onclick="console.log('hey, I am an arbitrary JS code');
jsf.ajax.request(this, event, {execute:'@this', render: 'result'});
return false;" />
Additionally, while f:ajax
does allow you to execute your JavaScript code when a request is complete, you really can't "call the java bean code" to get the data you want at this point. But you can put the data in the DOM using JSF Ajax, and get it from the DOM in your callback.
Here is an example to get you started, that gets data formatted in JSON:
A simple Bean method returning a string with a JSON encoded object:
public String getMyData() {
return "{\"fruit\": \"banana\"}";
}
View code:
<fieldset>
<h:form id="schedulerForm">
<h:commandButton value="Execute Demo" id="executeDemo">
<f:ajax event="click" listener="#{autoScheduler.executeDemo}"
render="result myHiddenData" onevent="parseData()" />
</h:commandButton>
<p />
<h:outputText id="result" value="#{autoScheduler.result}" />
<h:panelGroup id="myHiddenData" style="display: none">#{autoScheduler.myData}</h:panelGroup>
</h:form>
<script>
function parseData(data){
if (data.status == "success") {
var myRawData = document.getElementById("schedulerForm:myHiddenData").innerHTML;
var myJsonData = JSON.parse(myRawData);
alert(myJsonData.fruit);
}
}
</script>
</fieldset>
See also these related questions: