How to use shiny javascript functions?

China☆狼群 提交于 2020-12-28 20:59:58

问题


I want to send data from javascript to R using shiny js function, but is not working. What I have done is a simple example, in which setinputValue send "noone" to "too" input$too

Here is the code:

library(shiny)


ui <- fluidPage(

  HTML("<script>
       $( document ).ready(function() {
       Shiny.setInputValue('too', 'noone');

       });</script>"),


      textOutput("table")


  )


server <- function(input, output) {
 output$table <- renderPrint(input$too)


}

 shinyApp(ui,server)

The js error I get is: Shiny.setInputValue is not a function


回答1:


It does not work with $( document ).ready(function(), but with $( document ).on("shiny:sessioninitialized", function(event) {:

library(shiny)  
ui <- fluidPage(      
  HTML('<script>
       $( document ).on("shiny:sessioninitialized", function(event) {
           Shiny.onInputChange("too", "noone");           
       });</script>'),         
  textOutput("table")      
)

server <- function(input, output) {
  output$table <- renderPrint(input$too) 
}

shinyApp(ui,server)

Reason for this is given in the tutorial: You cannot call the function too soon, you need a little time until Shiny is ready to update the input value:

in message.js, we wrapped our code in $(document).ready(function() { ... }. This jQuery function will tell the browser to only run the code inside, once the page, i.e. the Document Object Model (DOM), is ready for JavaScript code to execute. Note that when we activate this code too soon, i.e. before the image is loaded, we cannot yet attach an event handler to it. In other words, here we want to be sure that the image exists before attaching an event handler to it. ```




回答2:


I just wanted to point out that the function being called in the answer by shosaco differs from original post which isn't that clear from the reasons why it didn't work.

Shiny.setInputValue('too', 'noone');

to

Shiny.onInputChange("too", "noone");           


来源:https://stackoverflow.com/questions/54039338/how-to-use-shiny-javascript-functions

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!