繁体   English   中英

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

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

我无法从javascript向Java控制器发送json对象,

阿贾克斯

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);
        }
    }
}

我在Java中尝试过的方法

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

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

它们都是空的。

我尝试阅读相关的文章以及多种发送数据的方法,但结果相同。 我不知道如何在Ajax中使用Jquery,所以我主要是在寻找js解决方案。

有人可以告诉我我所缺少的吗? 我花了大约三个小时试图弄清楚

要使JSON与POST请求一起发送,您必须在doPost方法中读取请求的正文 这是一种实现方法:

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();

然后,您必须解析JSON。 例如,可以使用Google gson完成此操作。

假设您有一个带有公共参数idtitle Thing类,这将是

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

当然,除了gson之外,还有其他解决方案可以解析JSON,但是您必须解析它。

我认为您正在将URL参数与请求正文混淆。 要从请求中获取json字符串,您需要从request.getReader()读取它。

我已经知道了。

Json应该这样发送:

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

代替

xmlHttp.send(jsonObj);

为了接收它作为参数。

暂无
暂无

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

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