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 ,现在打开网页,下拉列表就能显示数据了


  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值