1

I'm still new to RESTful APIs and JSON, so I tried looking at the documentation for jQuery and Play for sending JSON to a URI and parsing JSON from a request body.

Unfortunately, I'm getting some unexpected behavior.

Here is my AJAX call:

$.ajax({
            url: "@routes.Application.downloadResults",
            data: {
                uuid: $('body').attr('uuid')
            },
            dataType: 'json',
            contentType: "application/json; charset=utf-8",
            success: function(res) {
                console.log('success')
            },
            error: function(res) {
                console.log('error')
            }
        })

Here is my server code:

  def downloadResults = Action { request =>
    Logger.info("Attempting to download")
    Logger.info(request.toString)
    Logger.info(request.body.toString)
    Logger.info(request.body.asJson.toString)
    request.body.asJson.map { json =>
      {
    Logger.info(json.toString)
    json.validate[String].map {
      case uuid => {
        Logger.info(s"Looking for results-$uuid.txt")
        Ok.sendFile(new File(s"results-$uuid.txt"))
      }
    }.recoverTotal {
      e =>
        {
          Logger.info("Detected error: " + JsError.toFlatJson(e))
          BadRequest("Detected error: " + JsError.toFlatJson(e))
        }
    }
      }
    }.getOrElse {
      Logger.info("Expecting Json data")
      BadRequest("Expecting Json data")
    }
  }

Here is the resulting server log:

[info] application - Attempting to download
[info] application - GET /download?uuid=12512502-5ca4-47bc-a4db-15f1da1979fc
[info] application - AnyContentAsEmpty
[info] application - None
[info] application - Expecting Json data

Here is the resulting browser console:

GET http://localhost:9000/download?uuid=12512502-5ca4-47bc-a4db-15f1da1979fc 400 (Bad Request) jquery-1.9.0.min.js:3
error

It looks like the uuid is being attached to the URI as a parameter, but I was trying to send it as JSON. I guess it doesn't really matter which way it gets there right now, but I'm trying to sharpen up my understanding of using JSON for client-server communication. I tried calling Json.stringify on the JSON data, but that just resulted in GET /download?{%22uuid%22:%224de4c3dd-24db-49dc-8f9e-4d3e0d90dea5%22} in my server log.

Any tips on how to make this work?

4

1 回答 1

2

JQuery 在使用$.ajax(). 这就是您的内容附加到 URL 的原因。

您应该尝试添加type: "POST"到您的$.ajax通话中。这将告诉 jQuery 在请求正文中发送您的数据,而不是在 URL 中。

routes此外,请确保在应用程序配置文件中使用 POST 方法声明您的路由。

于 2013-05-24T19:10:04.117 回答