I am learning Ajax and trying to get it work on my project. Basically i am trying to implement google like suggestion on the project.
i have a UI that sends ajax request to the server asynchronously and gets relevant suggestion
function showHint(str) {
if (str.length == 0) {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
console.log(str);
var xmlhttp = new XMLHttpRequest();
console.log(xmlhttp.readyState);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET", "/hint?word=" + str, true);
xmlhttp.send();
}
}
<label>Name <input id="peak" type="text" name="peak_name" onkeyup="showHint(this.value)">
<p id="peak"></p>
<p>Suggestions: <span id="txtHint"></span></p>
The Spring MVC controller is
@RequestMapping(value = { "/hint" }, method = RequestMethod.GET,params={"word"})
public @ResponseBody ArrayList<String> hint(ModelMap model,@RequestParam String word) {
System.out.println("Inside Hint");
String[] hints = { "Ram", "Shyam" };
ArrayList<String> returnhint = new ArrayList<String>();
// lookup all hints from array if $q is different from ""
if (word != null) {
word = word.toLowerCase();
int length = returnhint.size();
for (int j = 0; j < length; j++) {
if (word.contains(hints[j])) {
returnhint.add(hints[j]);
}
}
}
return returnhint;
}
I am new to Ajax. So is there a specific way xmlhttp object's responseText have to be handled?
My question is since i have passed ArrayList in the response body, how do get ajax to get that response and update the UI accordingly?