别忘了纯Serlvet部属要在你的web.xml做配置。我的Serlvet的完整路进地址是::8080/JqueryStudy/chainSelect ,两句System.out.println()输出ajax传递过来的参数name和time。response.setCharacterEncoding(“UTF-8”)的作用是告诉浏览器字符串为utf-8的编码,防止中文乱码问题。response.setContentType(“application/json; charset=utf-8”)将返回的字符串以json格式形式返回。out对象是输出流,如果返回的是数组,格式应该如下:[“test1”, “test2”, “test3”],如果是json类,则格式如下:{“name”:”fly”,”type”:”虫子”}。
上诉案例返回的是json对象,后台控制台输出:
name = John
time = 2pm
前端浏览器的控制台输出:
name : fly
type : 虫子
Servlet返回数组的案例如下:
代码清单1.6:demo.java
import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class ChainSelect extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("name = " + request.getParameter("name")); System.out.println("time = " + request.getParameter("time")); response.setCharacterEncoding("UTF-8"); response.setContentType("application/json; charset=utf-8"); String jsonStr = "[\"test1\", \"test2\", \"test3\"]"; PrintWriter out = null; try { out = response.getWriter(); out.write(jsonStr); } catch (IOException e) { e.printStackTrace(); } finally { if (out != null) { out.close(); } } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
前端jQuery代码:
$(document).ready(function(){ //发起ajax请求 $.post("../chainSelect", {name: "John", time: "2pm"}, function(data){ for(var i = 0; i < data.length; i++) { console.log((i+1) + " : " + data[i]); } }, "json"); });
后台之需要给jsonStr赋值为数组格式而已,而前端jQuery代码由于接收到的字符串数组,所以这里需要用遍历数组的形式来遍历。
本案例的Servlet代码清单:
代码清单1.7:ChainSelect.java
import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class ChainSelect extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setCharacterEncoding("UTF-8"); response.setContentType("application/json; charset=utf-8"); String jsonStr = this.getStr(request.getParameter("keyword"), request.getParameter("type")); PrintWriter out = null; try { out = response.getWriter(); out.write(jsonStr); } catch (IOException e) { e.printStackTrace(); } finally { if (out != null) { out.close(); } } } private String getStr(String keyword, String type) { String jsonStr = ""; if("top".equals(type)) { if("BMW".equals(keyword)) { jsonStr = "[\"316ti\", \"6ercupe\"]"; } else if("Audi".equals(keyword)) { jsonStr = "[\"tt\"]"; } else if("VW".equals(keyword)) { jsonStr = "[\"Golf4\"]"; } } else if("sub".equals(type)) { if("tt".equals(keyword)) { jsonStr = "[\"rha\", \"rhb\", \"rhc\"]"; } else if("316ti".equals(keyword)) { jsonStr = "[\"rha\", \"rhb\"]"; } else if("6ercupe".equals(keyword)) { jsonStr = "[\"rha\", \"rhb\", \"rhc\"]"; } else if("Golf4".equals(keyword)) { jsonStr = "[\"rha\", \"rhb\"]"; } } return jsonStr; } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
代码清单1.7与清单1.6的区别是,后者多了getStr()的方法,该方法用于判断前端传递过来的是一级(top)下拉框的值,还是二级(sub)下拉框的值,并根据传递的keyword返回需要的字符串。与本后台交互的是程序清单1.8所示的代码。
程序清单1.8:chainSelect.js
/** * 级联下拉框效果 */ $(document).ready(function(){ //找到三个下拉框 var carnameSelect = $(".carname").children("select"); var cartypeSelect = $(".cartype").children("select"); var wheeltypeSelect = $(".wheeltype").children("select"); carnameSelect.change(function(){ var carname = carnameSelect.val(); if(carname != "") { //汽车厂商不为空发起ajax请求 $.post("../chainSelect", {keyword: carname, type : "top"}, function(data){ if(data != null && data.length != 0) { //清除上一次change的内容 cartypeSelect.html(""); $("<option value=''>请选择汽车类型</option>").appendTo(cartypeSelect); for(var i = 0; i < data.length; i++) { $("<option value='"+data[i]+"'>"+data[i]+"</option>").appendTo(cartypeSelect); } $(".cartype").show(); carnameSelect.next("img").show(); } }, "json"); } else { //3.如果值为空,那么第二个下拉框所在span要隐藏起来,第一个下拉框后面的指示图片也要隐藏 $(".cartype").hide(); $(".wheeltype").hide(); $(".carimage").hide(); $(this).next("img").hide(); } }); cartypeSelect.change(function(){ var cartype = cartypeSelect.val(); if(cartype != "") { //汽车类型不为空发起ajax请求 $.post("../chainSelect", {keyword: cartype, type : "sub"}, function(data){ if(data != null && data.length != 0) { //清除上一次change的内容 wheeltypeSelect.html(""); $("<option value=''>请选择车轮类型</option>").appendTo(wheeltypeSelect); for(var i = 0; i < data.length; i++) { $("<option value='"+data[i]+"'>"+data[i]+"</option>").appendTo(wheeltypeSelect); } $(".wheeltype").show(); cartypeSelect.next("img").show(); } }, "json"); } else { //汽车类型为空 $(".wheeltype").hide(); $(".carimage").hide(); $(this).next("img").hide(); } }); wheeltypeSelect.change(function(){ //选中的车轮类型 var wheeltype = wheeltypeSelect.val(); if(wheeltype != "") { //选中的车辆厂商 var carname = carnameSelect.val(); //选中的车辆类型 var cartype = cartypeSelect.val(); //图片的名称 var carimgName = carname + "_" + cartype + "_" + wheeltype + ".jpg"; console.log("carimgName : " + carimgName); $(".carimage").show(); $(".carimg").attr("src", "../image/" + carimgName).load(function(){ //隐藏loading图片 $(".carloading").hide("slow"); }); $(".carimage p img").show("slow"); } else { // alert("内容为空"); // $("img").hide(); $(".carimage").hide(); } }); //给数据装载中的节点定义ajax事件,实现动画提示效果 $(".loading").ajaxStart(function(){ $(this).css("visibility", "visible"); $(this).animate({ opacity: 1 },0); }).ajaxStop(function(){ $(this).animate({ opacity: 0 },500); }); });