我正在从客户端发出ajax POST请求。我的Play Framework控制器向返回JSON的跨域服务器发出请求。然后我想将此JSON转发给客户端。当我拨打Promise<JsonNode>.toString()
时,看来我收到了一个内存地址。如何将实际的JSON返回给客户端?
public static Result addVenue() {
final Map<String, String[]> values = request().body().asFormUrlEncoded();
String queryString = values.get("venueName")[0] + ",+" + values.get("venueAddress")[0] + ",+" + values.get("venueCity")[0] + ",+" + values.get("venueState")[0] + "+" + values.get("venueZip")[0];
String queryURL = "https://maps.googleapis.com/maps/api/place/textsearch/json?query=" + queryString + "&key=" + "AIzaSyD1xSgKUnEZ_tM7qzcEAeM-SJBxPFhIpaU";
queryURL = queryURL.replaceAll(" ", "+");
Promise<JsonNode> jsonPromise = WS.url(queryURL).get().map(
new Function<WSResponse, JsonNode>() {
public JsonNode apply(WSResponse response) {
JsonNode json = response.asJson();
return json;
}
}
);
response().setHeader("Access-Control-Allow-Origin", "*");
response().setHeader("Allow", "*");
response().setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, DELETE, OPTIONS");
response().setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Referer, User-Agent");
return ok(jsonPromise.toString());
}
答案 0 :(得分:2)
返回结果的承诺:
public static Promise<Result> addVenue() {
return WS.url(URL).get().map((response) -> {
return ok(response.asJson());
});
}
答案 1 :(得分:0)
我终于可以使用以下代码返回JSON。我的实现与提供的另一个答案略有不同。我将提供它以防万一另一个人不适合某些人。
final Promise<Result> resultPromise = WS.url(queryURL).get().map(
new Function<WSResponse, Result>() {
public Result apply(WSResponse response) {
Logger.info(response.asJson().toString());
return ok(response.asJson().toString());
}
}
);
return resultPromise;