1

我正在通过网页的发布请求向服务器发送数据。

$("#1, #2, #3, #4").on("click", function(){
            console.log($(this).attr("id"));
              var xhr = new XMLHttpRequest();
              xhr.open("POST", "SimpleServlet.html", true);
              xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
              xhr.send(JSON.stringify({"product_id": $(this).attr("id"), "quantity" : 1 }));
            });

在这个 javascript 的帮助下。我确信它会被发送到服务器并到达那里。

在服务器上,我尝试检索我写入数据的值。

.post("SimpleServlet.html", ctx ->
                    {
                        final Response response = ctx.getResponse();

                        System.out.println("Getting result");

                        final ExecResult<String> result = ExecHarness.yieldSingle(c ->
                                ctx.parse(String.class));


                        System.out.println("Getting value");
                        response.send("webshop.html");
                    })

不幸的是,我没有找到任何指导如何相应地检索字符串值。

我尝试了上述方法,但这确实永远卡在了 ExecHarness 中。

我想收到这些值。带他们创建一个新的 java 对象,然后返回另一个 java 对象的 json 响应。(第二个对象取决于之前的对象数据)

4

1 回答 1

2

Ratpack的 API 参考 而不是 ExecHarness 尝试这样的事情:

ctx.getRequest().getBody().then({ data ->
  String text = data.getText();
  // parse text with whatever you use, e.g. Jackson

  System.out.println("Getting value");
  response.send("webshop.html"); 
})

你也可以链接它,例如

context.getRequest().getBody().flatMap({ data ->
    //parse data and get id
    //call to async service who returns Promise
    return service.getReport(id).map((String report) -> {
        // do some staff
    })
 }).then({
     //final staff before send response
     //import static ratpack.jackson.Jackson.json; 
     context.getResponse().send(json(result).toString());
 })
于 2017-04-13T11:11:41.997 回答