views:

830

answers:

1

Hello All,

I am very new to using Jquery and Json. I have a servlet that is returning an array of JSONObject's ( basically a JSONArray object ).

I am trying to parse this array within JavaScript and am running into trouble here. I have a javascript variable "var result" that gets the result from the servlet and I am trying to parse it as result[0].uniqueId for example to get the value of uniqueId sent from the server. But this does not seeem to work.

Below is the Java servlet code snippet to show what gets sent to the javascript client.

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 // TODO Auto-generated method stub
                    JSONArray arrayObj = new JSONArray();
          List<Folder> children =getFolders(request,response);
          Iterator itr = children.iterator();
          while(itr.hasNext())
          {
           Folder folder = (Folder) itr.next();
           obj = new JSONObject();
           obj.put("uniqueId", folder.getUniqueId());
           obj.put("folderName", folder.getFolderName());
           obj.put("size", folder.getSize());
           obj.put("modified", folder.getModified());

           arrayObj.add(obj);
          }
         out = response.getWriter();
         response.setContentType("application/json");
         out.println(arrayObj);          
}

This is the jquery code snippet

$.ajax({
   url: 'getFolders',
   type: 'POST',
   data: 'uniqueID=' + uniqueID ,
   //console.log(data);
   success: function(result) {  
    //parse result
               alert("JSON result "+ result[0].uniqueId);

             }//end success
 });

Please advice as how to parse the result.

Thanks Deepthi

+3  A: 

You need to set the dataType option to the type of data you're expecting back from the server:

$.ajax({
              dataType: 'json',
              url: 'getFolders',
              type: 'POST',
              data: 'uniqueID=' + uniqueID ,
              //console.log(data);
              success: function(result) {  
              //parse result
                    alert("JSON result "+ result[0].uniqueId);

              }//end success
        });
karim79
Yes, jQuery ignores the `"application/json"` Content type in the response for some reason, so you need to specify `dataType`. IMO it's a bug (at a minimum it's inconsistent with how it acknowledges content types of `"application/xml"` or `"text/html"`).
Crescent Fresh
Woops, that last example was supposed to read `"text/xml"`.
Crescent Fresh