I'm currently working on a web application that displays a slideshow of images using the Cycle plug-in for jQuery. For ease of use, I'm making the application configurable, allowing someone to change the path for which the slide images can be found for displaying. I've found the necessary code to create all of the image filenames into one String array, but I'm not entirely sure how I can pass the whole array back to my jQuery for processing. I'm already using a Java Servlet as a proxy to get access to some RSS feeds, and so I decided to use the "$.get()" method to make an HTTP request with a tagged parameter to determine which functionality to carry out.
Long story short, how can I pass a String array to an HttpServletResponse variable so that it can be accessed like a String array in my jQuery? Here's some of the code I'm using thus far... Note: I'm brand new to both Java and JavaScript, including jQuery. I know my code is probably sloppy and/or inefficient.
---HERE'S THE JAVA SERVLET----
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.net.URL;
import javax.servlet.http.HttpServlet;
public class BBSServlet extends HttpServlet {
private void getSlidesList(final HttpServletResponse response) throws ServletException, IOException {
try {
File slidesdir = new File(AppConfiguration.getInstance().getSlidesDir());
if(slidesdir.isDirectory()) {
String slidenames[] = slidesdir.list();
// This is what I thought I could do...
final PrintWriter writer = response.getWriter();
for(int i = 0; i < slidenames.length; i++) {
writer.println(slidenames[i]);
}
// But I'm not sure if it works... }
} catch(final IOException e) {
e.printStackTrace();
}
}
public void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/xml");
final URL url;
if(request.getParameter("p").equals("w")) {
url = new URL(AppConfiguration.getInstance().getForecastUrl());
sendXML(response, url);
}
else if(request.getParameter("p").equals("n")) {
url = new URL(AppConfiguration.getInstance().getNewsUrl());
sendXML(response, url);
}
else if(request.getParameter("P").equals("f")) {
getSlidesList(response);
}
}
}
---jQuery js------------
// function called from the $(document).ready()
function DisplaySlides() {
$.get(baseContext + "/servlet?p=f", function(data) {
// "data" is hopefully a String array?
}
// display开发者_开发技巧 my slideshow with that array
}
I would suggest using a JSON Parser in Java such as Jackson to convert the string array to JSON. Then jQuery can read this and turn it into a javascript array with jQuery.getJSON.
精彩评论