如何从javascript检索json并传递给servlet并根据数据创建一个类

问题描述 投票:0回答:1

我有一个用户编辑表单,当我提交调用EditMain servlet时提交。我有一个JavaScript文件,可从中检索数据。

$(document).on("click","#main",function(){
    // Пример за заявка POST:
    postData('http://localhost:8080/javabeans/EditMain', toJSONString(document.forms[0]))
      .then((data) => {
        console.log(data); 
      });
});
async function postData(url = 'http://localhost:8080/javabeans/edit_profile.jsp', data = {}) {
      const response = await fetch(url, {
        method: 'POST',
        mode: 'cors',
        cache: 'no-cache',
        credentials: 'same-origin', 
        headers: {
          'Content-Type': 'application/json'
        },
        redirect: 'follow',
        referrerPolicy: 'no-referrer',
        body: data
      });
      return response.json();
}

   function toJSONString( form ) {
        var obj = {};
        var elements = form.querySelectorAll( "input, select, textarea" );
        for( var i = 0; i < elements.length; ++i ) {
            var element = elements[i];
            var name = element.name;
            var value = element.value;

            if( name ) {
                obj[ name ] = value;
            }
        }

        return JSON.stringify( obj );
    }

这是我的servlet类,当我从from调用函数时,我得到nullpointerException

    response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        Gson gson = new Gson();
        String requestData = request.getReader().lines().collect(Collectors.joining());
        out.println(requestData);
        User u = gson.fromJson(requestData, User.class);
        out.println(u.getName());

而且我在控制台中看到我得到响应,但没有json格式。这是我得到的

name=asd&job=asd&description=asdasdsa%09%09%09%09%09%09Some+long+description.............%0D%0A%0D%0A%09%09%09%09%09
javascript ajax asynchronous servlets gson
1个回答
0
投票

看起来响应是文本而不是json。

尝试

response.setContentType("application/json");

不是

response.setContentType("text/html;charset=UTF-8");

您可以在此处看到类似的内容:Servlet returning response as HTML instead of JSON

© www.soinside.com 2019 - 2024. All rights reserved.