简体   繁体   English

在Web应用程序中播放2.2返回Json响应

[英]Play 2.2 Return Json Response within Web Application

Is there a way to make a request RESTfully to a service that is on the same application and display it's response too? 有没有一种方法可以对同一应用程序上的服务进行RESTful请求并显示其响应? I've created a UI that has form parameters to fill out. 我创建了一个具有要填写的表单参数的UI。 When the user clicks submit, I'd like to have the response be embedded in the same page, displaying it to the user as json. 当用户单击“提交”时,我希望将响应嵌入到同一页面中,并以json的形式显示给用户。 I'd also like it to be able to be called externally of course, as it will be a restful api. 我也希望它能够在外部被调用,因为它将是一个宁静的API。

I can define in the routes file a path to return some json, but I'm not sure about how to consume it from the application itself. 我可以在路由文件中定义返回一些json的路径,但是我不确定如何从应用程序本身使用它。

I hope this is clear. 我希望这很清楚。 I'd be happy to provide more details if necessary. 如有必要,我很乐意提供更多详细信息。

Ok. 好。 First of all, let's consider that we have the route and controller that produce JSON response for us. 首先,让我们考虑一下我们具有为我们生成JSON响应的路由和控制器。

GET   /foo       controllers.FooController.foo

object FooController extends Controller
{
   .....

   implicit val fooWrites = Json.writes[Foo]
   def foo = Action {
       Ok(Json.toJson(Foo)).as("application/json")
   }

} }

Then we can use ajax from our page to get the response: 然后,我们可以使用页面中的ajax来获取响应:

<script>
  ......
   $.get("@routes.FooController.foo")
            .done(function(data){
                //do something with recieved data
        });
</script>

Or if you want to consume your data within your Play App,you may use WS lib. 或者,如果您想在Play App中使用数据,则可以使用WS lib。 For example. 例如。

object FooController extends Controller { 对象FooController扩展了控制器{

....
def fooConsumerController = Action.async {
  val fooJsonResultFuture =    
    WS.url("http://localhost:9000/foo").get().map(_.body)
    .....
     fooJsonResultFuture.map { json => 

       // do something with this result
       Ok(.....)
     }
  }
}

It's not very clear from your question, what behavior you want to achieve, but I hope it will help you to figure out some directions. 从您的问题尚不清楚,您想要实现什么行为,但是我希望它将帮助您找出一些方向。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM