'get json array from servlet using ajax

I have to json array in my servlet.

I want to fetch json array value and print in to jsp page using ajax.

below is code

JSONArray  htags = new JSONArray();
        htags.add("#abc");
        htags.add("#xyz");
        htags.add("#emc");
        htags.add("#netapp");


        //top trends
        JSONArray trends = new JSONArray();
        trends.add("pass");
        trends.add("horiz");
        trends.add("software");
        trends.add("banana");

jsp

I got error msg here.

$.ajax({

            url : "SerlvetToJsp",
            dataType : 'json',
            error : function() {

                alert("Error");
            },
            success : function(data) {
                alert(data);

            }
    });


Solution 1:[1]

See, if you want to pass that from servlet to jsp you need not to make a request (ajax), since servlet and jsp both exists at server side.You just set that json array as a request attribute or session attribute and get it in jsp and display(with loop).NO need of ajax there.

If You need to fetch the data with synchronous call:

In servlet

   PrintWriter out = response.getWriter();
   out.println(htags);

I won't clutter SO with another full example,see this SO post:How to send JSON array from server to client, i.e. (java to AJAX/Javascript)?

Solution 2:[2]

Try this

servlet code

JSONArray  htags = new JSONArray();
        htags.add("#abc");
        htags.add("#xyz");
        htags.add("#emc");
        htags.add("#netapp");


        //top trends
        JSONArray trends = new JSONArray();
        trends.add("pass");
        trends.add("horiz");
        trends.add("software");
        trends.add("banana");
response.setContentType("application/json"); 
response.setCharacterEncoding("utf-8"); 
String jsons = "["+htags+","+trends+"]"; //Put both objects in an array of 2 elements
out.print(jsons);

and on you jsp page

$.ajax({

            url : "SerlvetToJsp",
            dataType : 'json',
            contentType:"application/json",
            error : function() {

                alert("Error");
            },
            success : function(data) {
                var data1=data[0],
                var data2=data[2],
               alert(data1[0]);

            }
    });

Solution 3:[3]

Servlet can use this to send json array or json object to client.

JSONArray jsonArray = [{:}, {:}];

response.getWriter.write(jsonArray.toString());

In JSP page, this method call the request JSON to Servlet and catch the json array or json object with annonymous function(JSON.parse is used to convert string to json object or json array) method.

$("button").click(function(){
  $.get("ServletToJSP",function(data,status){
    alert("Data: " + JSON.parse(data) + "\nStatus: " + status);
  });
});

Solution 4:[4]

in servlet:

String uri = request.getRequestURI();
        if (uri.equalsIgnoreCase(uri)) {
                    response.setContentType("application/json");
                    /*   get the json array      */
                    response.getWriter().write(array.toJSONString());
                }

jquery:

    $('#buttonid').on('click', function() {
           var url="your url";
        $.ajax({
                type : 'POST',
                url : url,
                data : null,
                error : function(xhr, status, error) {
                    alert("error");
                },
                success : function(data) {
                    alert("success");
                    $.each(data, function(key, val) {
                    console.log(val);
                }
            });
    });

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Community
Solution 2
Solution 3 Aung Thuya
Solution 4 Mark Rotteveel