【问题标题】:Receiving data from .js in server.R shiny从 server.R 中的 .js 接收数据
【发布时间】:2015-11-15 10:42:41
【问题描述】:

我将如何接收在闪亮的server.R 中的.js 文件中创建的数据?

我正在使用 Leaflat 库,我需要扩展当前地图视图的 LatLngBounds。我需要server.R 中的这个变量进行进一步处理。

所以我有

 mycode.js

//get bounds of extend of view
$(document).ready(function() { 

var myBounds = map.getBounds();
Shiny.onInputChange("bounds", myBounds);



});

我把它包含在ui.R

tags$body(tags$script(src="mycode.js"))

这就是我的Server.R 的样子:

  myBoundsR <- reactive(
  as.numeric(input$bounds)
  print(input$bounds)
  )

但是,我将如何接收来自 mycode.jsserver.R 文件中的数据?

感觉Shiny.addCustomMessageHandler只能在.js(或.R)中接收数据,而session$sendCustomMessage只能在.R文件中使用?我会用什么来将.js 文件中的内容发送到server.R 文件?!

或者我可以像在server.R 文件中创建它一样简单地使用变量bound?!

【问题讨论】:

  • 你可以尝试在你的 javscript 中使用Shiny.onInputChange("var", data);,在你的server.R 中使用input$var 来获取变量。
  • @NicE 我不必绕道将变量存储在未显示的 div 容器中然后获取它?!喜欢这里的建议吗? stackoverflow.com/questions/23715614/… 因为当我这样写时 myBounds &lt;- observe(as.numeric(input$bound)) 它不起作用。我试图将它包装到 reactive 函数中,但也没有成功。
  • 你的意思是它不起作用。如果您不发布更多代码/我们可以运行的示例,很难帮助您。
  • @NicE 这就是我得到的错误Error in print(myBounds) : object 'myBounds' not found。我认为observe 函数没有收到来自js file 的变量?我在那里更新了我的代码。
  • 如果你想将它存储在某个东西中,需要是响应式的,你还需要在响应式表达式中使用print(input$bound)。不清楚 Number 在你的 javascript 中是什么,也许先尝试使用 Shiny.onInputChange("bound", "something"); 看看“某事”是否打印在你的 R 控制台中。如果是这样,那么问题可能出在您的 javascript 中。

标签: javascript r shiny shiny-server


【解决方案1】:

如果您想获取地图边界,可以使用input$map_bounds,如果 map 是您的传单地图的 id。

这是一个示例,(使用来自tutorial 的传单示例代码)

library(shiny)
library(leaflet)

r_colors <- rgb(t(col2rgb(colors()) / 255))
names(r_colors) <- colors()

ui <- fluidPage(
  leafletOutput("map")
    )
)

server <- function(input, output, session) {
  points <- cbind(rnorm(40) * 2 + 13, rnorm(40) + 48)

  observe({
    print(input$map_bounds)
  })
  output$map <- renderLeaflet({
    leaflet() %>%  addTiles() 
  })
}

shinyApp(ui, server)

【讨论】:

  • 您可以在页面末尾找到所有闪亮的绑定和输入/输出事件here
【解决方案2】:

关于 Nice 写的:

file.js

var myVariable = //do something
Shiny.onInputChange("variableNameToWriteInServer.R", myVariable)

server.R

observe({
# thats how you access the variable
    input$myVariable
#do something with the variable. To see if it worked something like
})

这应该可以解决问题。如果您使用getBounds() 函数,请记住Leaflet : Firing an event when bounds change。此外,您可能不会收到任何输出,因为当窗口扩展未更改时,getBounds() 函数不会返回窗口的边界。但是,它只执行一次。在我链接的文章中是一个解决方案。

有关 Shiny(server.R 和 ui.R)中进一步未记录的通信,请阅读此处:https://ryouready.wordpress.com/2013/11/20/sending-data-from-client-to-server-and-back-using-shiny/

【讨论】:

    猜你喜欢
    • 2014-05-16
    • 2012-11-20
    • 1970-01-01
    • 2014-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    相关资源
    最近更新 更多