一、HTML文件代码如下:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"> </script> <script> function getAjaxData() { let xmlHttpRequest; console.log("ada"); if(window.XMLHttpRequest) xmlHttpRequest = new XMLHttpRequest(); else xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP"); xmlHttpRequest.onreadystatechange=function () { if(xmlHttpRequest.readyState==4 && xmlHttpRequest.status==200){ const test = document.getElementById("test"); const text = xmlHttpRequest.responseText; test.innerHTML=text; console.log(text); } } xmlHttpRequest.open("GET","/getAjaxData",true); xmlHttpRequest.send(); } function getAjaxByPost() { let xmlHttp; if(window.XMLHttpRequest) xmlHttp = new XMLHttpRequest(); else xmlHttp = new ActiveXObject("Microsoft.XMPHTTP"); xmlHttp.onreadystatechange = function () { // const test = document.getElementById("test"); // test.innerHTML = xmlHttp.responseText; $("#test").html(xmlHttp.responseText); } xmlHttp.open("POST","getAjaxData",true); xmlHttp.setRequestHeader("Content-type","application/x-www-form-urlencoded"); xmlHttp.send("welcome=" + $("#welcome").val() + "&name=" + $("#name").val()); } </script> </head> <body> <div id = "test"> 要替换的内容 </div> <button type = "button " οnclick="getAjaxData()">从服务器获得数据</button> <label>请输入欢迎词:</label><input id ="welcome" /><br> <label>请输入姓名:</label><input id = "name"> <button οnclick="getAjaxByPost()">Post请求获得AJAX数据</button> </body> </html>
二、controller文件如下:
package com.ruoyi.web.controller; import org.apache.ibatis.annotations.Param; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PatchMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.ResponseBody; @Controller public class AjaxTest { @GetMapping("AjaxTest") public String ajaxTest(){ return "AjaxTest"; } @ResponseBody @GetMapping("/getAjaxData") public String getAjaxData(){ return "This Ajax Data from Server"; } @ResponseBody @PostMapping("/getAjaxData") public String postAjaxData(@Param("welcome") String welcome, @Param("name") String name){ return welcome + ":"+ name +"This Ajax Data from Server"; } }