2017-01-20 44 views
1

在JSF中使用ajax時遇到了一些麻煩。 事實上,我正在嘗試我要做的事很簡單,但我無法弄清楚。 我有返回一個字符串的方法,我只想打印這個字符串,當我點擊按鈕。這個方法需要2個參數,我想通過2個inputBox傳遞給方法。 這裏的代碼我提供了這麼遠,但它沒有完成,我不,如果我做的很好:在JSF中使用ajax

<h:commandButton id="submit" value="Submit"> 
      <f:ajax event="click" /> 
     </h:commandButton> 
     <h:outputText id="result" value="#{cSVobjectCtrl.getJson(48.866667, 2.33333)}" /> 

這段代碼的問題是,我得到直接的字符串之前,我按一下按鈕。我應該改變什麼才能讓代碼按我想要的方式工作。

編輯1:

<?xml version="1.0" encoding="UTF-8"?> 
<!-- 
To change this license header, choose License Headers in Project Properties. 
To change this template file, choose Tools | Templates 
and open the template in the editor. 
--> 
<!DOCTYPE html> 
<html xmlns="http://www.w3.org/1999/xhtml" 
     xmlns:h="http://xmlns.jcp.org/jsf/html" 
     xmlns:c="http://xmlns.jcp.org/jsp/jstl/core" 
     xmlns:f="http://xmlns.jcp.org/jsf/core"> 
    <h:head> 
     <title>JsonValue</title> 
     <meta name="viewport" content="width=device-width, initial-scale=1.0"/> 
     <script> 
     var show = function(){ 
     document.getElementById('result').style.display = 'block'; 
     } 
     </script> 
    </h:head> 

    <h:form> 


     <h:commandButton id="submit" value="Submit" onclick="show();" > 
    <f:ajax event="click" render="result"/> 
</h:commandButton> 
<h:outputText id="result" value="#{cSVobjectCtrl.getJson(48.866667, 2.33333)}" 
       style="display:'none'"/> 

    </h:form> 


</html> 

但問題仍然存在。字符串顯示在我點擊按鈕之前。

回答

1

這是爲我工作的解決方案:

JSF頁面

<h:commandButton id="submit" value="Submit"> 
     <f:ajax event="click" render="resultGroup" listener="#{cSVobjectCtrl.doRender}"/> 
</h:commandButton> 

<h:panelGroup id = "resultGroup" layout="block" > 
    <h:panelGroup rendered="#{cSVobjectCtrl.rendered}"> 
     <h:outputText id="result" value="#{cSVobjectCtrl.getJson(48.866667, 2.33333)}}" /> 
    </h:panelGroup> 
</h:panelGroup> 

輔助Bean

@ManagedBean 
@ViewScoped // this is important 
public class CSVobjectCtrl{ 

    private boolean rendered = false; 

    public boolean isRendered() { 
     return rendered; 
    } 

    public void setRendered(boolean rendered) { 
     this.rendered = rendered; 
    } 

    public void doRender(AjaxBehaviorEvent event){ 
     rendered = true; 
    } 
} 

在一邊,你有一個AJAX事件要明確指定刷新/渲染哪個組件(如果你不想做什麼):

render - 評估到集合。 組件的clientIds將參與請求處理生命週期的「呈現」部分。如果指定了文字,則標識符必須以空格 分隔。在標識符列表中可以指定任何關鍵字「@ this」,「@ form」,「@all」,「@none」 。如果未指定,則假定默認值爲「@none」 。例如,@ this clientIdOne clientIdTwo。

+0

Thx爲答案但我仍然有同樣的問題。我編輯了我的代碼,也許我做錯了什麼? –

+0

style =「display:none」.. none without quotes –

+0

好的,我已將輸出封裝在panelGroup中,並顯示/隱藏面板本身。試試吧 –