【问题标题】:Ajax response wait for future (scala)Ajax 响应等待未来(scala)
【发布时间】:2016-09-17 17:24:46
【问题描述】:

如果我在路由器的 post("/some") 路径中有 Future[A] 作为结果(最后一行),则 Ajax 客户端无法获得响应并超过超时。等待不起作用。 Future onComplete/onSuccess {...} 工作正常,但是对于服务器,那么如何将其作为响应翻译给客户端呢? (Scalatra 框架)

服务器:

post("/stations/test") {
  Future[Int] {
    // parse jsonData ...
    Thread.sleep(3000)
    1
  }.onComplete { x =>
    // do something on server ...
  }
}

客户:

@JSExport
def testFuture() = {
  val request = Ajax.post("/stations/test", jsonData)
}

【问题讨论】:

    标签: ajax scala future scalatra


    【解决方案1】:

    onComplete 返回Unit。但是,您需要从服务器向客户端发送正确的响应。在未来使用map 来创建响应。

    post("/stations/test") {
      Future[Int] {
        // parse jsonData ...
        Thread.sleep(3000)
        1
      }.map { data =>
        Response(data)
      }
    }
    

    【讨论】:

    • 谢谢!如果我输入响应(HttpServletResponse 的类型)而不是“响应(数据)”,它会很好地工作。周末愉快!客户端应该是这样的: Ajax.post("/stations/test", "abc") .recover { case dom.ext.AjaxException(req) => //... } .map(req => { / / 处理所有状态码 })
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多