如何从javascript正确启动/停止PrimeFaces Ajax Poll

时间:2015-02-16 02:26:06

标签: ajax primefaces ajax-polling

我想要一个小的webapp来测试与服务器的连接并返回状态消息。单击开始按钮后,我想每4秒轮询并返回一个状态文本。但它只会返回,如果我点击按钮,不会自动返回。 这是我的代码:

的index.xhtml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:ui="http://java.sun.com/jsf/facelets"
    xmlns:p="http://primefaces.org/ui">

<h:head>
</h:head>
    <h:body>
    <h1>My App</h1>
        <h:form onkeypress="poll.stop()">
            Server URL: <h:inputText id="name" value="#{helloBean.name}"></h:inputText>
            <p:commandButton value="Start Watching!" onclick="poll.start()" />

            <pre><h:outputText id="output" value="#{helloBean.playground}" /></pre>
            <p:poll interval="4" listener="#{helloBean.getPlayground}" update="output" widgetVar="poll" autoStart="false" />
        </h:form>
</h:body>
</html>

我的豆子:

@ManagedBean
@SessionScoped
public class HelloBean implements Serializable {
        public String getPlayground(){
        if(name.length() < 3){
            return "";
        }
        DateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy hh:mm:ss");
        Date date = new Date();
        String date1 = dateFormat.format(date);
        int code = 0;
        String urldns = null;
        try{
        URL url = new URL(name);
        HttpURLConnection connection = (HttpURLConnection)url.openConnection();
        connection.setRequestMethod("GET");
        connection.connect();
        code = connection.getResponseCode();
        urldns = connection.getURL().toString();
        connection.disconnect();
        }
        catch(Exception ex){
            name2.add(date1+" Uhr : "+name+" -> nicht erreichbar!");
        }

        if(code==200){
            if(urldns.contains("dnserror")){
                name2.add(date1+" Uhr : "+name+" -> nicht erreichbar!");
            }
            else{
                name2.add(date1+" Uhr : "+name+" ->  erreichbar ");
            }
        }
        startString = name+" wird überwacht. Taste drücken um abzubrechen...\n";
        String result = String.join("\n", name2);
        return startString+result;
    }
}

任何人都可以帮助我吗?因为我是PF和Ajax的新手。谢谢!

1 个答案:

答案 0 :(得分:6)

我看到没有人回答你的消息。所以,让我们尝试一下我的建议。

如果您使用的是&#34;最新版本&#34;我认为调查的调用存在错误。

我正在使用PrimeFaces 5.1,如果您想通过javascript与您的民意调查进行互动,解决方案是:

PF('poll').start();

PF('poll').stop();

我还想建议避免在窗体上监听关键事件,但是使用jQuery在窗体或页面上注册事件监听器,而不是停止在回调函数中使用的轮询(给出看看here)。

如果您在更新结果时遇到问题,请尝试更新其他结构

<pre>
  <p:outputPanel id="output">
    <h:outputText value="#{helloBean.playground}" />
  </p:outputPanel>
</pre>
<p:poll interval="4" listener="#{helloBean.getPlayground}" 
        update="output" widgetVar="poll" autoStart="false" />

希望这会有所帮助! 祝你好运

的Davide