2017-04-09 129 views
0

我通過網頁發送數據到服務器發送數據。Ratpack無法從主體檢索價值

$("#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迴應。 (二對象依賴於一個對象的數據)

回答

1

Ratpack's API reference 相反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()); 
})