简体   繁体   中英

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? I've created a UI that has form parameters to fill out. 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. I'd also like it to be able to be called externally of course, as it will be a restful 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.

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.

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:

<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. For example.

object FooController extends Controller {

....
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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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