使用Spring MVC在Ajax响应中获得406错误

时间:2016-08-23 08:15:07

标签: javascript ajax spring spring-mvc

我正在学习Ajax并尝试让它在我的项目上运行。基本上我正在尝试在项目上实施谷歌般的建议。
我有一个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>
&#13;
&#13;
&#13;

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?

2 个答案:

答案 0 :(得分:0)

要使用@ResponseBody,您需要做两件事:

    您的上下文文件中的
  • <mvc:annotation-driven />
  • 在你的类路径中处理JSon(如Faster Jackson)的库

如果您没有正确配置弹簧部件,则会出现406错误,因为响应的标头未正确初始化且响应本身格式不正确。

答案 1 :(得分:0)

通过documentation,xmlhttprequest对象有一组处理响应的属性

  

XMLHttpRequest.response只读
  返回ArrayBuffer,Blob,Document,JavaScript对象或DOMString,具体取决于XMLHttpRequest.responseType的值。包含响应实体主体。

所以我基本上返回了一个String而不是一个ArrayList,并使用逗号','separator

连接字符串中所有匹配的提示

并在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;

}

希望这将有助于未来的ajax学习者使用spring mvc。