简体   繁体   中英

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

I need to submit a form in ajax manner. 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.

  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

 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 string = "example"; // The String which you wish to convert JsonObject convertedObject = new Gson().fromJson(string, JsonObject.class);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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