3

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

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>

消息.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文件中的错误。

4

2 回答 2

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!");
        }
      });
于 2013-04-12T13:55:06.303 回答
0

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

于 2013-04-12T13:47:18.493 回答