简体   繁体   English

将servelt中的字符串转成json数据传给javascript:ajax

[英]convert the string in servelt to json data and pass it to javascript : ajax

I need to submit a form in ajax manner.我需要以 ajax 方式提交表单。 when form submits convert the string inside the servlet to json data and pass it to the javascript function and display these errors separately near to the error div tag below each input field.当表单提交时,将 servlet 中的字符串转换为 json 数据并将其传递给 javascript 函数,并在每个输入字段下方的错误 div 标记附近分别显示这些错误。

  if(firstparamtr-condition)
    {
        String firsterror = "Error first";

        response.setContentType("application/json");

        response.setHeader("Cache-Control", "no-cache");

        response.setCharacterEncoding("UTF-8");         

        response.getWriter().write(firsterror);       

    }

   if(secondparamtr-condition)
    {
        String seconderror = "Error second";

        response.setContentType("application/json");

        response.setHeader("Cache-Control", "no-cache");

        response.setCharacterEncoding("UTF-8");         

        response.getWriter().write(seconderror);       

    }

javascript code javascript代码

 posting.done(function( responseText ) {

   alert(responseText);

//HERE I need to separate the responseText and show that errors in the div tags named 'firstEr' and 'secondEr'      

      });

For converting String to JSON I use the GSON convertor, an example below:为了将 String 转换为 JSON,我使用GSON转换器,示例如下:

String string = "example"; // The String which you wish to convert JsonObject convertedObject = new Gson().fromJson(string, JsonObject.class);

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

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