简体   繁体   English

使用Ajax Post将JSON从JS发送到控制器

[英]Sending json from js to controller with ajax post

I'm having trouble sending a json object from javascript to java controller, 我无法从javascript向Java控制器发送json对象,

Ajax : 阿贾克斯

var xmlHttp = getXmlHttpRequestObject();
if(xmlHttp) {
        var jsonObj = JSON.stringify({"title": "Hello","id": 5 });
        xmlHttp.open("POST","myController",true);
        xmlHttp.onreadystatechange = handleServletPost;
        xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xmlHttp.send(jsonObj);
    }
function handleServletPost() {
    if (xmlHttp.readyState == 4) {
        if(xmlHttp.status == 200) {
            alert(window.succes);
        }
    }
}

What I tried in Java: 我在Java中尝试过的方法

public void process(
        final HttpServletRequest request, final HttpServletResponse response,
        final ServletContext servletContext, final TemplateEngine templateEngine) 
        throws Exception {

     String jsonObj = request.getParameter("jsonObj");
}

They all are null. 它们都是空的。

I tried reading related posts and multiple ways of sending the data but same result. 我尝试阅读相关的文章以及多种发送数据的方法,但结果相同。 I don't know how to use Jquery for ajax, so I'm looking for a js solution mainly. 我不知道如何在Ajax中使用Jquery,所以我主要是在寻找js解决方案。

Can someone tell me what I'm missing? 有人可以告诉我我所缺少的吗? As I spent about three hours trying to figure it out 我花了大约三个小时试图弄清楚

To get your JSON sent with a POST request, you have to read the body of the request in a doPost method. 要使JSON与POST请求一起发送,您必须在doPost方法中读取请求的正文 Here's one way to do it : 这是一种实现方法:

protected void doPost(HttpServletRequest hreq, HttpServletResponse hres)
throws ServletException, IOException {
    StringWriter sw = new StringWriter();
    IOUtils.copy(hreq.getInputStream(), sw, "UTF-8");
    String json = sw.toString();

And then you'll have to parse the JSON. 然后,您必须解析JSON。 This may be done for example using Google gson . 例如,可以使用Google gson完成此操作。

Supposing you have a class Thing with public parameters id and title , this would be 假设您有一个带有公共参数idtitle Thing类,这将是

Gson gson = new GsonBuilder().create();
Thing thing = gson.fromJson(json, Thing.class);
int id = thing.id;
String title = thing.title;

Of course there are other solutions than gson to parse JSON but you have to parse it. 当然,除了gson之外,还有其他解决方案可以解析JSON,但是您必须解析它。

I think you are confusing URL parameters with request body. 我认为您正在将URL参数与请求正文混淆。 To get json string from request you need read it from request.getReader() . 要从请求中获取json字符串,您需要从request.getReader()读取它。

I have figured it out. 我已经知道了。

The Json should be sent like this: Json应该这样发送:

xmlHttp.send("jsonObj="+jsonObj);

instead of 代替

xmlHttp.send(jsonObj);

In order to receive it as parameter. 为了接收它作为参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM