1. 前臺jsp,新建一個下拉控件
<select id="seldvd" onChange="sel_onchange(this)"></select>
2. js部分,建一個function方法,利用ajax,指向 'getAllTypes.action' 的servlet部分,獲取傳來的下拉列表的數據,動態填充
<span style="white-space:pre"> </span>function loadType(){ <span style="white-space:pre"> </span>$.get( <span style="white-space:pre"> </span> 'getAllTypes.action', <span style="white-space:pre"> </span> function(data){ <span style="white-space:pre"> </span> var $sel = $("#seldvd"); <span style="white-space:pre"> </span> // console.log(data); <span style="white-space:pre"> </span> for(var i = 0;i<data.length;i++){ <span style="white-space:pre"> </span> <span style="white-space:pre"> </span>$item = $("<option></option>"); //添加option <span style="white-space:pre"> </span> <span style="white-space:pre"> </span>$item.val(data[i].id); //添加option的value ,<span style="line-height: 1.5; white-space: pre-wrap; font-family: Arial, Helvetica, sans-serif;"><span style="font-size:10px;">數據庫中用id和type保存的數據</span></span> <span style="white-space:pre"> </span> <span style="white-space:pre"> </span>$item.html(data[i].type); //添加option數據 <span style="white-space:pre"> </span> <span style="white-space:pre"> </span>$sel.append($item); //將option添加進select <span style="white-space:pre"> </span> } <span style="white-space:pre"> </span> },'json' <span style="white-space:pre"> </span> ); <span style="white-space:pre"> </span>}
3. 新建一個servlet頁面,用來向Ajax返回數據
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); ArrayList<typeInfo> typeList = new ArrayList<typeInfo>(); typeDao td = new typeDao(); typeList = td.getAllTypes(); JSONArray arr = new JSONArray(typeList);//這里導入需要轉json數據包 String jsString = arr.toString(); //響應到客戶端 request.setCharacterEncoding("utf-8"); response.setContentType("text/plain;charset=utf-8"); response.getWriter().print(jsString); //返回下拉列表需要的json格式數據 }
4. 那么問題來了,這個數據來源在哪???當然在數據庫(MySQL)。所以先要寫一個方法讀取數據庫中的數據
<strong>typeInfo.java</strong>
import java.io.Serializable; public class typeInfo implements Serializable { private int id; private String type; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getType() { return type; } public void setType(String type) { this.type = type; } public typeInfo(){ } public typeInfo(int id, String type) { this.id = id; this.type = type; } }
新聞熱點
疑難解答
圖片精選