safoora safu safoora safu - 27 days ago 6
CSS Question

javascript array length is 1

I am using javascript for creating a filter. I am using ajax and collecting value.
Ajax Request:

if(window.XMLHttpRequest)
{
vendreq=new XMLHttpRequest();
}
else
{
vendreq=new ActiveXObject("Microsoft.XMLHTTP");
}

vendreq.onreadystatechange=function () {
/* if(b==0){
document.getElementById("details2").innerHTML="Select GIT more than 0";
} */
if((vendreq.readyState==4) && (vendreq.status==200)) {
venda= [];

venda.push(vendreq.responseText);
alert(venda.length);

} }
vendreq.open("Get","Vendor","true");
vendreq.send();
});


Servlet Vendor:

ResultSet rs =ps.executeQuery();
while(rs.next()){
out.println(rs.getString("VNAME")+",");
out.println(rs.getString("VCODE")+",");
}


when I display i.e alert(venda) it displays multiple values. where as when I check for the array length , it shows one. Can any one tell me what is the reason for this?

filter:

<div class="optionsDiv2" style="display:inline;">
Filter by Vendor <select name="item" id="vendor">
vendb=document.getElementsByName("venda");
while(vendb.length) {
<option>vendb</option>

}
</select>
</div>

Answer

As per I understand from your response text template, you are receiving values like:

VNAME1,
VCODE1,
VNAME2,
VCODE2,
...
VNAME(N),
VCODE(N),

It would be great if you save result in an object and then return it in the form of json.

It would look similar to:

"VALUES":[{
    "VNAME": "VNAME1",
    "VCODE": "VCODE1"
}, {
    "VNAME": "VNAME2",
    "VCODE": "VCODE2"
},
... {
    "VNAME": "VNAME(N)",
    "VCODE": "VCODE(N)"
}]

Also for your current situation (As you are returning a plain string) I would suggest you to use a unique splitter for string to create an array

out.println(rs.getString("VNAME")+",");
out.println(rs.getString("VCODE")+"+++");

So it'll return string as:

VNAME1,
VCODE1+++
VNAME2,
VCODE2+++

Now remove venda= []; and instead of venda.push(vendreq.responseText); use venda = vendreq.responseText.split("+++"); That'll create an array of your returned string as "VNAME1,VCODE1","VNAME2,VCODE2"...

And trust me its a bad implementation method. Use JSON instead.

Added snippet for example:

str="VNAME1,VCODE1+++VNAME2,VCODE2+++VNAME3,VCODE3+++";
venda=str.split("+++");
alert(venda.length-1 +" Values: "+venda);

Comments