ajax - Display a JSON object made in java in jsp using javascript -


hello trying make json object in java , want display same json object in jsp using javascript. basically, want add 2 more options in select box using ajax. ajax getting called , in response cans see following o/p not able add vales in dropdown. please help... want javascript only.

{"value1":"label1","value2":"label2"} 

java code:

map<string, string> options = new linkedhashmap<string, string>(); options.put("value1", "label1"); options.put("value2", "label2");  string json = new gson().tojson(options); //  json = "dataobject: [" +json+ "]"; system.out.println(json);  response.setcontenttype("application/json"); response.setcharacterencoding("utf-8"); response.setheader( "pragma", "no-cache" ); response.setheader( "cache-control", "no-cache" ); response.setdateheader( "expires", 0 ); response.getwriter().write(json); 

javascript :

xmlhttp.onreadystatechange=function() {     if (xmlhttp.readystate==4 && xmlhttp.status==200)     {         var responsejson=xmlhttp.responsetext;         alert(responsejson);         var carobj = eval ("(" + responsejson + ")");         select = document.getelementbyid("selector");         (var = 0; < carobj.dataobject.length; i++) {             var d = carobj.dataobject[i];             select.appendchild(new option(d.value1, d.value2));         }     } }; 

jsp :

<select id="selector" onchange="showstate(this.value)" >     <option value="volvo">volvo</option>     <option value="saab">saab</option>     <option value="mercedes">mercedes</option>     <option value="audi">audi</option> </select> 

there's no dataobject in json. it's object, not array, can't use .length or numeric indexes. use for (key in obj) iterate on properties.

xmlhttp.onreadystatechange = function() {   if (xmlhttp.readystate == 4 && xmlhttp.status == 200) {     var responsejson = xmlhttp.responsetext;     alert(responsejson);     var carobj = json.parse(responsejson);     select = document.getelementbyid("selector");     (var value in carobj) {       select.appendchild(new option(value, carobj[value]));     }   } }; 

Comments

Popular posts from this blog

python - pip install -U PySide error -

arrays - C++ error: a brace-enclosed initializer is not allowed here before ‘{’ token -

cytoscape.js - How to add nodes to Dagre layout with Cytoscape -