日期:2014-05-16 浏览次数:20403 次
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Untitled Document</title> <script type="text/javascript" src="jquery-1.6.1.js"> </script> <script language="JavaScript"> $(function(){ $("#s1").change(function(){ var obj = $("#s1");//取得下拉列表框对象 s1 // alert(obj); //2. 取得Options 的长度 len = $('#s1 option').length // alert(len); //3. 取得所选值 注意,如果option没有value属性,则默认取的是text属性值 obj_value = $('#s1').val(); // alert("$('#s1').val()"+obj_value); // alert($('#s2').val()); //4. 取得所选中的option var opt = $("#s1 option:selected"); ; // alert("opt:"+opt); // alert(opt.text()); // alert(opt.val()); var url = "../jsonServlet"; var param = "name=" + $("#s1 option:selected").text(); alert(param); $.ajax({ type: "POST", url: url, data: param, cache: false, dataType: "json", success: function(msg){ //jsonServlet 返回的是一个JSONArray alert(msg); //清空下拉列表框 $("#s2").empty(); //遍历数组 $.each(msg, function(i, text){ alert("数组的索引:" + i); alert("数组的值:" + text); //增加option $("#s2").append("<option>" + text + "</option>") }); } }) }); }) </script> </head> <body> <p align="center"> jquery+ json--省市二级联动 </p> <table align="center"> <tr> <td> 省份 </td> <td> <select id="s1"> <option value="1">省份</option> <option value="2">湖北</option> <option value="3">浙江</option> </select> </td> <td> <select id="s2"> <option>城市</option> </select> </td> </tr> </table> </body> </html>
后台:JsonServlet.java
package com.wepull.servlet; 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; import net.sf.json.JSONArray; public class JsonServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletExcep