1

I have a servlet list:

String appname=request.getParameter("AppID");
System.out.println("Entered ajax request 1 : Get list");
List<Object> li = Model.getList(appname);
// enter your code here

I have an AJAX call which is taking that list from the servlet:

$(document).ready(function() {
    $('#app-name').change(function () {
        var applname=$(this).value();
        $.ajax({
              url: '${pageContext.request.contextPath}/rollreturn',
              data: {AppID:applname},
              success: function(data){
                  var order_data = data;
                  $('#roll-name').html('');
                  $.each(order_data, function(i, item) {
                      $('<option value='+ order_data[i] +'>'+order_data[i]).html('</options>').appendTo('#roll-name');
                  });
              }
        });
    });
});

How can I pass the list to the AJAX call. Can you help me with this?

Also can you tell me whether the AJAX call I have written is correct or not?

mmvsbg
  • 3,570
  • 17
  • 52
  • 73
Sushin K.Kumar
  • 149
  • 1
  • 3
  • 12

2 Answers2

0

By setting the content type in servlet.

response.setContentType("application/json");

new Gson().toJson(li, response.getWriter());

result in ajax you will receive an JSON object so you have to parse it.

There are many ways of parsing JSON object in JSP/HTML file. A simple example

See Demo

You can also parse your JSON object using JSTL tag and scriplet tag.

See this question

Community
  • 1
  • 1
KhAn SaAb
  • 5,248
  • 5
  • 31
  • 52
0

you can also use OutputStream to write list values from servlet

To download gson jar here

import java.io.OutputStream;
import com.google.gson.Gson;

In your doGet/doPost method

ArrayList<Object> listresult=new ArrayList<Object>();

listresult.add("values1");
listresult.add("values2");
listresult.add("values3");
listresult.add("values4");

response.setContentType("application/json");
OutputStream outputStream= response.getOutputStream();
Gson gson=new Gson();       
outputStream.write(gson.toJson(listresult).getBytes());
outputStream.flush();

To retrieve values in ajax success function

success: function(result){
for(var i=0;i<result.length;i++)
{           
 alert(result[i]);
}
},

Answer is too late, It helps some others

Asha
  • 750
  • 1
  • 6
  • 22