0

I am communicating servlet to jQuery in following way.

jQuery:

$('.snd').click(function (){
    $.ajax({
        url: '/ProjectName/ServletName?action=test',
        data: {cl1: $('.t11').val()},
        success: function (response){
            $('.t12').val(response);
        }
    }); 
});

Servlet

if (action.compareTo("test") == 0) {
            action = "abc";

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

            try {

                out.println("text1");
            } finally {
                out.close();
            }
        }

By doing this I am getting the result "text1"

Now what do I need to do if instead of sending normal text I want to send an object or an String array to the jQuery as response?

e.g

in servlet I have the following array

String[] ss= {"n1","n2"};

and in jQuery I want to use

$('.t12').val(response[0]);

to get result "n1"

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
LynAs
  • 6,407
  • 14
  • 48
  • 83
  • 1
    HTTP only sends and receives strings. It's up to you to determine how those strings are interpreted, e.g., JSON or other forms of type conversion. – Dave Newton Apr 22 '13 at 22:12

1 Answers1

3

You can't send objects directly between server and browser, but what you can do is serialize them into the JSON text format (that's what JSON was invented for). JSON.serialize() (or equivalent in other languages) on the server side and JSON.parse() on the client side.

If you specify the data type as JSON in the jQuery ajax call, it will automatically parse it for you so you don't even have to call JSON.parse().

jfriend00
  • 683,504
  • 96
  • 985
  • 979