我正在学习Ajax,并试图使其在我的项目中起作用。基本上我想在项目上实现谷歌一样的建议。
我有一个UI,该UI异步将ajax请求发送到服务器并获得相关建议
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>
Spring MVC控制器是
@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;
}
我是Ajax的新手。那么,是否有必须处理xmlhttp对象的responseText的特定方式?
我的问题是,由于我已经在响应正文中传递了ArrayList,如何获取Ajax以获取该响应并相应地更新UI?
在文档中,xmlhttprequest对象具有一组属性来处理响应
XMLHttpRequest.response只读
返回一个ArrayBuffer,Blob,Document,JavaScript对象或DOMString,具体取决于XMLHttpRequest.responseType的值。包含响应实体主体。
因此,我基本上返回了一个String而不是ArrayList,并使用逗号','分隔符将字符串中所有匹配的提示连接在一起
并在javascript文件中。我只是使用split(',')函数列出了响应列表。
function showHint(str) {
if (str.length == 0) {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
console.log(str);
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var list=xmlhttp.responseText.split(',');
console.log(list);
document.getElementById("txtHint").innerHTML = list;
}
};
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>
控制器方式
@RequestMapping(value = { "/hint" }, method = RequestMethod.GET,params={"word"})
public @ResponseBody String hint(ModelMap model,@RequestParam String word) {
System.out.println("Inside Hint");
String[] hints = { "Ram", "Ra","R","Shyam" };
String returnedhints="";
// lookup all hints from array if $q is different from ""
if (word != null) {
System.out.println("i am here");
//word = word.toLowerCase();
int length = hints.length;
for (int j = 0; j < length; j++) {
System.out.println(word+"contains"+hints[j]+"="+word.contains(hints[j]));
if ((word.regionMatches(0, hints[j], 0, hints[j].length())) {
returnedhints= returnedhints+","+hints[j];
}
}
}
return returnedhints;
}
希望这对使用Spring MVC的未来Ajax学习者有所帮助。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句