0

当我将数据发布到 Scalatra 路由时,看不到任何参数。

在客户端:

$.ajax({
    type: 'POST',
    url: window.location.origin + '/move',
    contentType: 'application/octet-stream; charset=utf-8',
    data: {gameId: 1, from: from.toUpperCase(), to: to.toUpperCase()},
    success: function(result) {
        console.log('ok posting move', result);
    },
    error: function(e) {
        console.log('error posting move', e);
    }
});

在开发工具网络视图中:

Payload
gameId=1&from=B1&to=C3

在 Scalatra 路线中:

params("gameId") // -> java.util.NoSuchElementException: key not found: gameId

但是,如果我通过删除数据字段并将 url 设置为:

    type: 'POST',
    url: window.location.origin + '/move?gameId=1&from=' + 
        from.toUpperCase() + '&to=' + to.toUpperCase(),

然后 Scalatra 可以看到参数 OK,即使将参数放在帖子的查询字符串中似乎是错误的。

为什么 Scalatra 在发布数据时看不到任何参数?

4

1 回答 1

1

您需要application/x-www-form-urlencoded用作内容类型:

script(type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js")

:javascript
  $(function() {
    $("#btn").click(function() {
      $.ajax({
        type: 'POST',
        url: window.location.origin + '/form',
        contentType: 'application/x-www-form-urlencoded; charset=utf-8',
        data: {gameId: 1, from: "FROM", to: "TO"}
      });
    });
  });


span#btn hello

在您的 Scalatra 应用程序中:

post("/form") {
  val payload = for {
    gameId <- params.getAs[Int]("gameId")
    from <- params.getAs[String]("from")
    to <- params.getAs[String]("to")
  } yield (gameId, from, to)

  payload
}       

有关详细信息,请查看Servlet 规范

于 2013-08-10T20:03:03.853 回答