play framework 2.0 json - 接收null JsonNode对象

时间:2013-04-12 10:51:13

标签: java json playframework

我在以下代码中获取了一个空的JsonNode对象。客户端javascript出了问题。如果我使用POST请求运行curl命令,我会得到正确的响应。如果我在下面提到的Javascript中运行相同的东西 - 我为JsonNode对象得到一个null。这是代码

Application.java
package controllers;

import org.codehaus.jackson.JsonNode;

import play.Routes;
import play.mvc.Controller;
import play.mvc.Result;
import views.html.index;


public class Application extends Controller {

    public static Result index() {
        return ok(index.render("Your new application is ready."));
    }

    public static Result receiveData() {
      response().setContentType("application/json");
      JsonNode json = request().body().asJson();
      if(json == null) {
        return badRequest("Expecting Json data");
      } else {
        String name = json.findPath("name").getTextValue();
        if(name == null) {
          return badRequest("Missing parameter [name]");
        } else {
          return ok("Hello " + name);
        }
      }
    }

    public static Result javascriptRoutes() {
      response().setContentType("text/javascript");
      return ok(
        Routes.javascriptRouter("jsRoutes",
          // Routes
          controllers.routes.javascript.Application.receiveData()
        )
      );
    }

}


Routes
# This file defines all application routes (Higher priority routes first)
# ~~~~

# Home page
GET     /                           controllers.Application.index()
POST    /receiveData                controllers.Application.receiveData()
GET    /assets/javascripts/routes   controllers.Application.javascriptRoutes()

# Map static resources from the /public folder to the /assets URL path
GET     /assets/*file               controllers.Assets.at(path="/public", file)

main.scala.html

@(title: String)(content: Html)
@import helper._
@import controllers.routes.javascript._

<!DOCTYPE html>

<html>
    <head>
        <title>@title</title>
        <link rel="stylesheet" media="screen" href="@routes.Assets.at("stylesheets/main.css")">
        <link rel="stylesheet" media="screen" href="@routes.Assets.at("stylesheets/bootstrap.css")">
        <link rel="shortcut icon" type="image/png" href="@routes.Assets.at("images/favicon.png")">
        <script type="text/javascript" src="@routes.Application.javascriptRoutes"></script>
        <script src="@routes.Assets.at("javascripts/jquery-1.9.0.min.js")" type="text/javascript"></script>
        <script src="@routes.Assets.at("javascripts/bootstrap.js")" type="text/javascript"></script>
        <script src="@routes.Assets.at("javascripts/message.js")" type="text/javascript"></script>

    </head>
    <body>
        <div class="container">
          <div class = "row">
            <div class = "span12">
              <input type = "text" id = "inputValue" value="getData"></input>
              <button class = "approveButton btn btn-primary">Approve </button>
            </div>
          </div>
        </div>

    </body>
</html>

message.js

$(document).ready(function(){
  $('.approveButton'). click(function(){
      var value = $('#inputValue').val();
      var jsonToSend = {};
      jsonToSend.name = value;
      var outputData = JSON.stringify(jsonToSend);
      jsRoutes.controllers.Application.receiveData().ajax({
        data:outputData,
        contentType:'application/json',
        success: function(data) {
          console.log(data);
        },
        error: function() {
          alert("Error!");
        }
      });
    });
  });

这是curl命令的输出:

curl --header "Content-type:application/json" --request POST --data '{"name":"abx"}' http://localhost:9000/receiveData
Hello abx

有人可以帮助识别javascript文件中的错误。

2 个答案:

答案 0 :(得分:2)

ajax调用的预期结果是json对象。在这种情况下,如果您想使用纯文本进行回复,请将 dataType:'text'添加到请求中:

jsRoutes.controllers.Application.receiveData().ajax({
        data:outputData,
        dataType: 'text',
        contentType:'application/json',
        success: function(data) {
          console.log(data);
        },
        error: function() {
          alert("Error!");
        }
      });

答案 1 :(得分:0)

也许是一个愚蠢的问题,但你认为,ajax调用将是POST而不是GET?您是否尝试过GET替换POST?