日期:2014-05-16  浏览次数:20362 次

js ajax传回数组 向select中添加options
下面的例子是根据选择省份,查出省份下的仓库

js页面:
<html>
<head>
<script type="text/javascript">
var xhr=false;

function createXHR(){
try{
xhr=new XMLHttpRequest();
}catch(e){
try{
xhr=new ActiveXObject("Msxml2.XMLHTTP");
}catch(e1){
try{
xhr=new ActiveXObject("Microsoft.XMLHTTP");
}catch(e2){
xhr=false;
}
}
}
if(!xhr){
alert("对不起,您现在所使用的浏览器,无法创建XMLHttpRequest对象");
}
}

function porChange(){
createXHR();
var proid=document.getElementById("pro").value;
var url="<%=request.getContextPath()%>/cameraOperate.do?method=getPro&proid="+proid;
xhr.open("POST",url,true);
xhr.onreadystatechange=callback;

xhr.send(null);
}

function callback(){
if(xhr.readyState==4){
if(xhr.status==200){
var warehouses=eval(xhr.responseText);
var ware=document.getElementById("warehouse_id");
ware.options.length=0;
var op1;
if(warehouses!=null){
  for(var i = 0; i<warehouses.length;i++){  
ware.add(new Option(warehouses[i]["name"], warehouses[i]["id"]));
    }
}
}
}
}
</script>
</head>
<body>
<tr>
<td align="right" width="10%">所属库所在省份:</td>
<td align="left" width="20%">
<select id="pro" name="pro"  style="width:200" onchange="porChange();">
<c:forEach items="${prolist}" var="pr" varStatus="p">
<option value="${pr.id}">${pr.name}</option>
</c:forEach>
</select>
<script>
for(var i=0;i<document.getElementById('pro').options.length;i++){
if(document.getElementById('pro').options[i].value==='${cameraOperateForm.proid}'){
document.getElementById('pro').options[i].selected=true;
}
}
</script>
</td>
</tr>
<tr class="common">
<td align="right" width="8%">所属库:</td>
<td align="left" width="20%">
<html:select styleId="warehouse_id" name="cameraOperateForm" property="warehouseid" style="width:200" value="warehouse_id.name">
<html:options  collection="warehouses" labelProperty="name" property="id" />
</html:select>
<script>
document.getElementById("warehouse_id").value="${cameraOperateForm.warehouse_id.id}";
</script>
<font color="red">*</font>
</td>
</tr>
</body>
</html>

java界面(我这里用的是struts1,原理都是一样的)
public ActionForward execute(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)throws Exception
{
CameraOperateForm cameraOperateForm = (CameraOperateForm)form;
CameraService cameraService = (CameraService)getWebApplicationContext().getBean("cameraService");
CameraOperateVo camerOperateVo = new CameraOperateVo();
if("getPro".equals(cameraOperateForm.getMethod())){
WareHouseService wareHouseService = (WareHouseService)getWebApplicationContext().getBean("wareHouseService");
List<DictWarehouse> warehouses=wareHouseService.getWareHouseByProvinceId(cameraOperateForm.getProid());
//下面是把集合循环出来,获得数组中的对象,并用对象的id,name值组成String 的json形式,写入流。在后台就可以获取到json
String js