Javascript 将数据从js发送到R变量
我试图通过javascript发送get请求,并将响应带到Javascript 将数据从js发送到R变量,javascript,r,shiny,Javascript,R,Shiny,我试图通过javascript发送get请求,并将响应带到input$myinfo。当我启动应用程序时,我可以在dev tools的Sources选项卡中看到该文件,但它似乎不起作用。 下面是我的js文件的外观: $(() => { $.ajax({ method : "GET", url : window.location.origin + "/mypath" }) .done(data => {
input$myinfo
。当我启动应用程序时,我可以在dev tools的Sources
选项卡中看到该文件,但它似乎不起作用。
下面是我的js文件的外观:
$(() => {
$.ajax({
method : "GET",
url : window.location.origin + "/mypath"
})
.done(data => {
Shiny.onInputChange('myinfo', JSON.stringify(data.responseJSON));
})
.fail(data => {
console.log(data.responseText);
});
});
然后将其加载到
ui.R
中,并(据我所知)在应用程序启动时运行。但它似乎永远不会进入输入$myinfo
,因为它看起来是空的。我缺少什么?我认为您需要利用shinny:connected
事件。您正在等待文档准备就绪,但还需要等待shiny准备就绪。该页面涉及相关事件并提供更多详细信息
我举了一个小例子。裸露的shinny.onInputChange(..)
抱怨没有shinny
对象(请参见浏览器开发人员控制台),并且input$missing
为NULL
。但是,等待shinny:connected
事件的shinniputchange(..)
将通过input$found
为“[1,2,3,4,5]”
库(闪亮)
在准备就绪时,您可以发布一个可复制的示例吗?您的浏览器JavaScript控制台中是否存在任何错误?您是否看到未捕获类型错误:shinny.onInputChange不是一个函数
?如果是,请参阅。如果没有,请检查WebSocket请求,以查看输入更改是否确实已发送。@gregL控制台中没有错误,尽管我设法使其使用$(document).ready(function(){
而不是$(()=>{
和其他一些我不确定是否记得正确的操作。控制台抛出未捕获的TypeError:shinny.onInputChange不是一个函数,以及如何在shinny模块中复制它。foundValue
命名空间更改为someid foundValue
?
library(shiny)
on_ready <- paste(
"$(function() {",
"$(document).on('shiny:connected', function(e) {",
"Shiny.onInputChange('found', JSON.stringify([1, 2, 3, 4, 5]));",
"});",
"Shiny.onInputChange('missing', JSON.stringify(['where', 'am', 'I?']));",
"",
"});",
sep = "\n"
)
ui <- fluidPage(
tags$head(
tags$script(on_ready)
),
fluidRow(
column(
6,
h5("`input$missing`:"),
verbatimTextOutput("missingValue"),
p("(error, Shiny object is missing as connection is not yet established)")
),
column(
6,
h5("`input$found`:"),
verbatimTextOutput("foundValue"),
p("(no error, wait for `shiny:connected` event)")
)
)
)
server <- function(input, output) {
output$missingValue <- renderPrint({
input$missing
})
output$foundValue <- renderPrint({
input$found
})
}
shinyApp(ui, server)