如果觉得写得可以 或者太差 就 评论一下或者赞一下呗,多谢支持!!
<!-- https://mvnrepository.com/artifact/org.json/json -->
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20160810</version>
</dependency>
2. jsp页面代码
<%@ page language="java" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>用户登陆</title> <script src="js/jquery-1.7.1.min.js"></script> </head> <script type="text/javascript"> var xmlHttp; function createXmlHttpRequest(){ try { // Firefox, Opera 8.0+, Safari xmlHttp=new XMLHttpRequest(); } catch (e) { // Internet Explorer try { xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { alert("您的浏览器不支持AJAX!"); return false; } } } } function btn_click() { //创建XMLHttpRequest对象 createXmlHttpRequest(); //获取值 var username = document.getElementById("txt_username").value; var age = document.getElementById("txt_age").value; //配置XMLHttpRequest对象 xmlHttp.open("get", "login.do?username=" + username + "&age=" + age); //设置回调函数 xmlHttp.onreadystatechange = callBackMethod; //发送请求 xmlHttp.send(null); } function callBackMethod(){ if (xmlHttp.readyState == 4) { if (xmlHttp.status == 200) {//http请求一切正常 var result = xmlHttp.responseText; alert(eval('('+result+')')["msg"]); } else { alert("Not able to retrieve description" + XMLHttpReq.statusText); } } else { switch (xmlHttp.readyState) { case 0: alert("未初始化 还没有调用send()方法"); break; case 1: alert("载入 已调用send()方法,正在发送请求"); break; case 2: alert("(载入完成)send()方法执行完成,已经接收到全部响应内容"); break; case 3: alert("(交互)正在解析响应内容"); break; } } } </script> <body> <label for="txt_username"> 姓名:</label> <input type="text" id="txt_username" /> <br /> <label for="txt_age"> 年龄:</label> <input type="text" id="txt_age" /> <br /> <input type="button" value="GET" id="btn" onclick="btn_click();" /> <div id="result"> </div> </body>
3.spring 的controller
import org.json.JSONObject; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import java.util.HashMap; /** * Created by Administrator on 2017\9\4 0004. */ @Controller public class loginController { @ResponseBody @RequestMapping(value="login.do",method = RequestMethod.GET) public String login( @RequestParam(value = "username")String name, @RequestParam(value = "age")String age ){ HashMap<String,String> map = new HashMap<>(); if(name.equals("123")){ map.put("msg","success"); }else{ map.put("msg","fail"); } String jsonAllGoods = JSONObject.valueToString(map); return jsonAllGoods; } }