0

I made a ajax call from my jsp to servlet. when I want to return string then it is working fine. But I want to send response as a String array then its not working. Is it possible that I can send string array from servlet as a ajax response.

  String[] roleAccess=null; 
              response.setContentType("text/html");
                         try{
                            roleAccess=new String[23];
                            roleAccess[0]="";
                            roleAccess[1]="checked";
                            roleAccess[2]="";

 response.getWriter().write(roleAccess.toString());---this part I need to change.
Praveen
  • 55,303
  • 33
  • 133
  • 164
Ashish
  • 51
  • 1
  • 4
  • 9

3 Answers3

0

Write it out to JSON instead. Javascript can't understand the result of a Java array's toString() method ([Ljava.lang.String;@5527f4f9), but I know it can understand JSON.

If you're only ever going to be using a string array and you don't want to use any more libraries:

public static String toJSON(String[] array)
{
    String json = "[\"";

    for (String s : array)
    {
        json += s + "\",\"";
    }

    return json.substring(0, json.length() - 2) + "]";
}

Depending on what Javascript framework you're using on your client-side, your JSON will be available as the xmlHttpRequestObject.responseText. AngularJS stores it in the $http.get().success method's first data parameter. jQuery stores it in the $.ajax({success}) method's first data parameter. Angular and jQuery automatically validate and eval it to an [object Object] for you, but xmlHttpRequestObject.responseText doesn't.

citizenslave
  • 1,408
  • 13
  • 25
0

Send the ajax response in json format by encoding the array in json and return it.

You can use Gson and then encode your array like:

String jsonRoleAccess = new Gson().toJson(roleAccess, roleAccess.class);
response.getWriter().write(jsonRoleAccess);

// OR do a one liner:
response.getWriter().write(new Gson().toJson(roleAccess, roleAccess.class));

And on the Javascript end, you can access it as a json object

// Assuming you've read the ajax response into var roleAccess
var checked = roleAccess[1];
Joshua Kissoon
  • 3,269
  • 6
  • 32
  • 58
0

You want to marshall the array as a JSON data type. The format returned by Java's array class is not in a format that JavaScript understands.

You should also wrap your array inside of an Object because of a security issue of passing top-level arrays back as JSON.

See Why are top level json arrays a security risk

Community
  • 1
  • 1
BeWarned
  • 2,280
  • 1
  • 15
  • 22