代码如下,数据能从数据库正确读取,问题是JSP不能向JS的数组正确添加数据,望高手指点迷津。
function findprod(locationid){
var subcat = new Array();
var id=locationid;
xml = new ActiveXObject("Microsoft.XMLHTTP");
xml.open("POST","mytest.jsp?i="+id+"",false);
xml.send();
<%
int count=0;
String tid=request.getParameter("i");
Set select=new HashSet();
String p_brand="";
String hqla="select distinct PBrand from DiyProd where t_id='"+tid+"'";
if(tid!=null){
List prods=hn.query(hqla);
Iterator it=prods.iterator();
while(it.hasNext()){
p_brand=(String)it.next();
System.out.println(count);
System.out.println(p_brand+"---");
%>
subcat[<%=count%>]='<%=p_brand%>';
<%
count++;
}
}
%>
}
function findprod(locationid){
var subcat = new Array();
var id=locationid;
xml = new ActiveXObject("Microsoft.XMLHTTP");
xml.open("POST","mytest.jsp?i="+id+"",false);
xml.send();
<%
int count=0;
String tid=request.getParameter("i");
Set select=new HashSet();
String p_brand="";
String hqla="select distinct PBrand from DiyProd where t_id='"+tid+"'";
if(tid!=null){
List prods=hn.query(hqla);
Iterator it=prods.iterator();
while(it.hasNext()){
p_brand=(String)it.next();
System.out.println(count);
System.out.println(p_brand+"---");
%>
subcat[<%=count%>]='<%=p_brand%>';
<%
count++;
}
}
%>
}
System.out.println(count);
System.out.println(p_brand+"---");
这两行的代码是有值。
但检查JS的数组元素时,用alert发现里面并没有值,而是undefined
function findprod(locationid){
var id=locationid;
xml = new ActiveXObject("Microsoft.XMLHTTP");
xml.open("POST","mytest.jsp?i="+id+"",false);
xml.send();
<%
int count=0;
String tid=request.getParameter("i");
Set select=new HashSet();
String p_brand="";
String hqla="select distinct PBrand from DiyProd where t_id='"+tid+"'";
if(tid!=null){
List prods=hn.query(hqla);
%>
var subcat = new Array(<%=prods.size()%>); [color=#FF0000]// 声明js数组时要给出数组的大小[/color]<%
Iterator it=prods.iterator();
while(it.hasNext()){
p_brand=(String)it.next();
System.out.println(count);
System.out.println(p_brand+"---");
%>
subcat[ <%=count%>]=' <%=p_brand%>';
<%
count++;
}
}
%>
}
看看subcat数组定义的情况
function findprod(locationid){
var id=locationid;
xml = new ActiveXObject("Microsoft.XMLHTTP");
xml.open("POST","mytest.jsp?i="+id+"",false);
xml.send();
<%
int count=0;
String tid=request.getParameter("i");
Set select=new HashSet();
String p_brand="";
String hqla="select distinct PBrand from DiyProd where t_id='"+tid+"'";
if(tid!=null){
List prods=hn.query(hqla);
%>
var subcat = new Array(<%=prods.size()%>); // 声明js数组时要给出数组的大小
<%
Iterator it=prods.iterator();
while(it.hasNext()){
p_brand=(String)it.next();
System.out.println(count);
System.out.println(p_brand+"---");
%>
subcat[ parseInt(<%=count%>)]=' <%=p_brand%>'; // // 这里需要转换一下类型
<%
count++;
}
}
%>
}
<%
int count=1;
%>
<html>
<head>
<script>
function getJSPValue(){
alert(<%=count%>);
}
</script>
</head>
<body>
<input type="button" onclick="getJSPValue();" value="点击">
</body>
</html>
数组应该也会了吧
改为alert("<%=count%>");