将数据发送到Shiny服务器并返回发生延迟

时间:2014-07-02 19:00:43

标签: r shiny

我希望通过按方形div /按钮(页面上的第3个元素),元素下方会出现一个随机数字,元素的颜色也会改变。不幸的是,似乎我必须按下页面顶部的按钮才能实现这一点,我无法弄清楚原因?

我的 index.html

<html>
    <head>
        <script type="text/javascript" src="shared/jquery.js"></script>
        <script type="text/javascript" src="shared/shiny.js"></script>
    </head>

    <body>
        <input id="button" type="submit" name="submit" value="Press me!" class="action-button">
        <p><div id="text" class="shiny-text-output" style="width: 150px; height: 25px; border: 1px solid black;"></div>
        <p><div id="mydiv" style="width: 50px; height: 50px;"></div>
        <pre id="results" class="shiny-text-output"></pre>
    </body>

    <script type="text/javascript">
        // send data to shiny server
        document.getElementById ("mydiv").onclick = function() {
            var number = Math.random();
            Shiny.onInputChange ("mydata", number);
        };

        // handlers to receive data from server
        Shiny.addCustomMessageHandler ("myColorHandler",
            function (color) {
                document.getElementById ("mydiv").style.backgroundColor = color;
            }
        );
    </script>
</html>

我的 server.R

shinyServer (function (input, output, session)
{
    observe ({
        x = input$button;

        output$text = renderText ({
            if (! is.null (x))
            {
                if (x %% 2 == 0) { paste (x, ": you are even", sep=""); }
                else { paste (x, ": you are odd", sep=""); }
            }
        })
    });

    output$results = renderPrint ({
        input$mydata;
    })

    observe ({
        input$mydata;
        color = rgb (runif (1), runif (1), runif (1));
        session$sendCustomMessage (type="myColorHandler", color);
    });
})

1 个答案:

答案 0 :(得分:0)

将按钮上的type="submit"更改为type="button"。目前,您的按钮的行为是submitButton,而不是actionButton

<html>
    <head>
        <script type="text/javascript" src="shared/jquery.js"></script>
        <script type="text/javascript" src="shared/shiny.js"></script>
    </head>

    <body>
        <input id="button" type="button" name="submit" value="Press me!" class="action-button">
        <p><div id="text" class="shiny-text-output" style="width: 150px; height: 25px; border: 1px solid black;"></div>
        <p><div id="mydiv" style="width: 50px; height: 50px;"></div>
        <pre id="results" class="shiny-text-output"></pre>
    </body>

    <script type="text/javascript">
        // send data to shiny server
        document.getElementById ("mydiv").onclick = function() {
            var number = Math.random();
            Shiny.onInputChange ("mydata", number);
        };

        // handlers to receive data from server
        Shiny.addCustomMessageHandler ("myColorHandler",
            function (color) {
                document.getElementById ("mydiv").style.backgroundColor = color;
            }
        );
    </script>
</html>