Reputation: 169
I have a JSP including three dropdown boxes called "countries","regions" and "cities". My aim is to populate regions from countries and cities from regions. I did it with parameters using Java and Javascript on same page but, in any click on dropdown lists, the page refreshes itself. I dont want it to be refreshed at everyclick on dropdown lists.
The data of "countries", "regions" and "cities" comes from JSON data on Java part "<%...%>" on same page.
I tried to do it with AJAX but couldn't find working example to pass parameters. If its required to separate the whole page into small JSPs such as "countries.jsp", "regions.jsp", "cities.jsp", I can do it but I need to solve the parameter passing between them. I would like to get the parameters as Ajax call on same page WITHOUT USING JQUERY. I need to do it with pure JS.
Im looking for your suggestions and working examples of JSP Ajax including parameters.
Upvotes: 1
Views: 6281
Reputation: 2716
First, I think you want to break things up into a regions.jsp and cities.jsp ( countries will always stay the same, right?). Next you need to attach a function that grabs the values from countries when it changes, using the OnChange event, and passes it to your regions.jsp. Like this:
<select name-"countries" id-"countries" OnChange="getRegions();"><option> ...</option></selct>
Then you implement javascript to make the ajax call, like this (no jquery required)
var requestObj = false;
if (window.XMLHttpRequest) {
requestObj = new XMLHttpRequest();
} else if (window.ActiveXObject) {
requestObj = new ActiveXObject("Microsoft.XMLHTTP");
}
function getRegions()
{
var select = document.getElementById('countries');
var currentCountry = select.options[select.selectedIndex];
if (requestObj) {
requestObj.open("GET", "/ajax/regions.jsp?country=" + currentCountry);
requestObj.onreadystatechange = function ()
{
if (requestObj.readyState == 4 && requestObj.status == 200) {
var options = parseJSON(requestObj.responseText);
for( var i=0; i<options.length; i++) {
document.getElementById("regions").appendChild("<option value='" + options['id'] + "'>" + options['text'] + "</option>");
}
}
}
requestObj.send(null);
}
}
Whew what a blast from the past with no jquery. This make sense?
Upvotes: 1