1. 程式人生 > >Ajax動態為下拉列表新增資料

Ajax動態為下拉列表新增資料

1. 前臺jsp,新建一個下拉控制元件

        <select id="seldvd" onChange="sel_onchange(this)"></select>

2. js部分,建一個function方法,利用ajax,指向 'getAllTypes.action' 的servlet部分,獲取傳來的下拉列表的資料,動態填充
function loadType(){
 $.get(
  'getAllTypes.action',
  function(data){
  var $sel = $("#seldvd");
  // console.log(data);
  for(var i = 0;i<data.length;i++){
    $item = $("<option></option>");  //新增option
    $item.val(data[i].id);  //新增option的value ,資料庫中用id和type儲存的資料
$item.html(data[i].type); //新增option資料 $sel.append($item); //將option新增進select } },'json' ); }
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)。所以先要寫一個方法讀取資料庫中的資料
typeInfo.java
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;
	}
	
	

}
TypeDao.java  (需要匯入JDBC包)
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;

import model.typeInfo;

public class typeDao extends baseDao {
	
	public ArrayList<typeInfo> getAllTypes(){
		ArrayList<typeInfo> typeList = new ArrayList<typeInfo>();
		
		Connection con = null;
		PreparedStatement psm = null;
		ResultSet rs = null;
		
		try {
			con = super.getConnection();
			psm = con.prepareStatement("select * from types");
			rs = psm.executeQuery();
			while(rs.next()){
				typeInfo types = new typeInfo();
				types.setId(rs.getInt(1));
				types.setType(rs.getString(2));
				
				typeList.add(types);
			}
			
		} catch (Exception e) {
			System.out.println("顯示所有型別報錯:"+e.getMessage());
		}finally{
			super.closeAll(rs, psm, con);
		}
		
		
		return typeList;
	//	
	}
}
4. 好了,利用Tomcat ,現在開啟網頁,下拉列表就能顯示資料了