1.前台调用ajax访问后台方法,并接收数据
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>success</title> </head> <script type="text/javascript"> function ajax(url, fnSucc) { if (window.XMLHttpRequest) { var oAjax = new XMLHttpRequest(); } else { var oAjax = new ActiveXObject("Microsoft.XMLHTTP");//IE6浏览器创建ajax对象 } oAjax.open("GET", url, true);//把要读取的参数的传过来。 oAjax.send(); oAjax.onreadystatechange = function () { if (oAjax.readyState == 4) { if (oAjax.status == 200) { fnSucc(oAjax.responseText);//成功的时候调用这个方法 } else { if (fnfiled) { fnField(oAjax.status); } } } }; } function change() { ajax('/abc2?user="wangerxiao"', function (str) { alert(str); }) } </script> <body> <h1>this is success page</h1> <h2>${msg}</h2> <div class="form" style=" 100px;height: 100px;background-color: red" onclick="change()"> </div> </body> </html>
2.后台处理请求返回数据map以及list
@Controller public class HelloController { @GetMapping("/abc2") @ResponseBody public Map<String,Object> hello2(@RequestParam("user")String user){
System.out.println(user); List<String> list = new ArrayList<>(); list.add("a"); list.add("b"); list.add("c"); Map<String,Object> map = new HashMap<>(); map.put("1","王二小"); map.put("2","刘明"); map.put("3","张三"); return map; } }