JSF 2.0: ajax request when press ENTER

2020-08-17 17:51发布

问题:

i need to do an ajax request when i click "enter" in inputText field, without refresh page. That's my code:

<h:form id="form-test">
   <p:growl id="messages" showDetail="true"/>
   <p:inputText id="inputEnter" 
             onkeypress="if (event.keyCode == 13) {onchange(); return false; }" 
             value="#{bean.content}">
       <f:ajax event="change" listener="#{bean.save}" update="messages"/>
   </p:inputText>
</h:form>

And in bean I have a simple method:

public void save(AjaxBehaviorEvent event){
  ...
}

All works, but It refresh page !!! Why ? How can I solve it ?

回答1:

There is already a thread with a question somehow like yours How to handle the ENTER keypressed to trigger an onBlur() event?

I would just change

onkeypress="if (event.keyCode == 13) {e.preventDefault();
inputEnter.onchange(); return false; }" 

If you use JQuery

$('#form-test\\:inputEnter').onchange();


回答2:

I think you need to enter the render param , so it does not render the whole page again.

<h:form id="form-test">
   <p:growl id="messages" showDetail="true"/>
   <p:inputText id="inputEnter" 
             onkeypress="if (event.keyCode == 13) {onchange(); return false; }" 
             value="#{bean.content}">
       <f:ajax event="change" render="messages" listener="#{bean.save}" update="messages"/>
   </p:inputText>
</h:form>


标签: ajax jsf