Ajax向Controller发送请求并接受数据需要注意的一个细节

想用Ajax想向Controller发送请求和接收返回的字符等等。Controller中要使用@ResponseBody注解。

<script type="text/javascript">
    function loadXMLDoc()
    {
        if (window.XMLHttpRequest){
            
            var request = new XMLHttpRequest();
            var url = "http://localhost:8080/TestJson/ajaxController/testAjax?time=" + new Date();
            
        //open中的第三个参数要用true,表示异步的
            request.open("GET", url, true);
            request.send();
            
            request.onreadystatechange = function(){
                if(request.readyState == 4 && request.status == 200){
                    document.getElementById("myDiv").innerHTML=request.responseText;
                }
            }
        }else{
        }
    }
</script>

----

@RequestMapping(value="testAjax", method=RequestMethod.GET)
    public @ResponseBody String testAjax(@RequestParam(name="time") String time, ModelAndView modelAndView) throws InterruptedException
    {
//        Thread.sleep(8000);
        System.out.println("请求发送到服务器");
        System.out.println(time);
        
        modelAndView.setViewName("testAsync");
        String link = "<a href='http://www.baidu.com'>www.baidu.com</a>";
        return link;
    }
原文地址:https://www.cnblogs.com/GooPolaris/p/7919854.html