Search code examples
javascriptajaxjsonliferay-6arrays

Pass JsonArray data from serveResource to jsp and display on JSP - Liferay


I have a jsp where I have a dropdown box. Whenever a user selects any item from the dropdown box its information should be displayed. For this I am using ajax. I have created serveResource function to pass the data for this purpose The following code is serveResource function where I collect data from database and store it in JSONArray as follows:

   JSONArray jsonArray = JSONFactoryUtil.createJSONArray();
   jsonArray.put(syudname.toString());
   jsonArray.put(studdiv.toString());
   jsonArray.put(studimageURL);

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

The data is successfully displayed on jsp using success function of ajax. The code for this is as follows:

 type: 'POST', 
    dataType : "json", 
        success : function(jsonArray) { 

            alert(jsonArray);

            $('#studDetails').append(jsonArray[0]+"<br/>");
            $('#studDetails').append(jsonArray[1]+"<br/>");
            $('#studDetails').append(jsonArray[2]+"<br/>");
            var image = jsonArray[2];
            alert(image);

        } 

Whenever i select any item from dropbox, its information (which I retrieve usinng jsonarray) is displayed. But the problem comes when I select another item from the dropbox..at this point, the data of the newly selected item is appended to the previosly selected item's data. i was using .html() function before instead of .html() for this when i wasnt having jsonarray. when i use .html() for jsonarray only the last element of the array is diplayed. How can I avoid this? my second problem is that instead of image its path is getting displayed.how should i diplay image please note that studDetails above is the id of the div where i am displaying all the data..


Solution

  • something like this:

    $('#studDetails').html(jsonArray[0]+"<br/>" + jsonArray[1]+"<br/>" + "<img src='" + jsonArray[2] + "'/><br/>");