Hello, I am currently working on creating a Json object in Java and would like to display the same JSON object in JSP using JavaScript. Essentially, I am looking to add two more options in my select box using Ajax. The Ajax is being called and I can see the output in the response, but I am having trouble adding the values to the dropdown. Any assistance would be greatly appreciated. I am aiming to achieve this using 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");
for (var i = 0; i < 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>