简体   繁体   中英

using javascript variable in bean jsf

I'm trying to use a javascript var in the bean variable. This variable is the index that I need to get all values from my object. But it doesn't recognize, how can I do this? Or can you help me with an alternative solution. Thanks.

function cargarCategorias() {
    while ( indice <= 5){
        var valor = "#{ctrDashboard.objReporte1.get(indice)[0]}";
        categorias.push(valor);
   }
}

You seem to misunderstand that Java code ( ctrDashboard.getObjReporte1.get(indice)[0] ) operates on the server machine and JavaScript code ( function cargarCategorias() { ... } ) operates on the client machine within the context of webbrowser. Thus, you can't directly use these two languages interchangingly. But still, understanding lifecycle of JSF framework will help you achieve your goal.

So, your problem can be solved by using different tools. For example, if you want to preload a set of data to a JS context upon initial GET request on the page, you need to have an array of elements in JS while the page is being rendered:

<script type="text/javascript">
    var valors = #{bean.valorsJson};
</script>

with bean method as:

public String getValorsJson() {
    return new Gson.toJson(valorList);
}

I proposed to use Gson library for the purpose, but you're free to choose a way of creating JSON object yourself.

With this approach you will use a JavaScript variable valors for traversal in your JS function.

The similar approach can be taken if you want to update your array via AJAX.

The last thing worth noting is that this is merely a trick that is usually used to overcome a drawback in your design of JSF application. It could indicate both that you're using a wrong framework for the job mentioned and that you failed to find a proper instrument within JSF, but that's impossible to know given the information disclosed so far.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM