1

I am trying to write a single Array object using PrintWriter.out.write() as a response to a JavaScript (AJAX) function,
Is this possible? or will I need to convert the array in same manner before sending?
Trying to avoid creation of comma separated String and then parsing in JS

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException {

    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    out.write(listDir());
}


private File[] listDir(){

    File folder = new File("/home/rob/");
    File[] listOfFiles = folder.listFiles();

    //System.out.println("Number of files found: " + listOfFiles.length);

    return listOfFiles;
}

Would like to then iterate through the files within the calling JavaScript AJAX function:

if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {

    for (var i = 0; i < xmlhttp.responseText.length; i++) {
        alert(xmlhttp.responseText[i]);
    } 
}
bobbyrne01
  • 6,295
  • 19
  • 80
  • 150
  • Since you don't want to make your response from the Servlet in Text format, you will have to convert the result to JSON format, you could check a good example in this answer http://stackoverflow.com/a/4113258/2727401 – fujy Sep 01 '13 at 22:28

1 Answers1

4

Java's array objects don't have an implementation of toString() method. As such, your output from

out.write(listDir());

will look something like

[Ljava.io.File;@5d9d277e

You definitely don't want this. There are many ways to serialize arrays. One of these is to separate the elements by ,

out.write(Arrays.toString(listDir()));

gives you something like

[some.txt, other.png]

Other formats include JSON and XML. Since Javascript comes with a built-in JSON parser, I would suggest you use JSON. You can find a Java JSON library here. Change the content-type if you return something like JSON (ex. application/json).

Community
  • 1
  • 1
Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724