概述
本文通过实现登录功能,讲解 前端发送 AJAX 请求,springboot 接收 AJAX 请求,返回JSON
前端发AJAX请求
jquery
jquery封装了 发送 AJAX 请求,使用更加简单
下载 jquery (右键另存为)
html代码
当前只是讲解 发送 AJAX 请求,没有传递数据
手机号:<input type="text" id="phone" /><br>
密码:<input type="password" id="password" /><br>
<input type="button" value="登录" onclick="doLogin()"/>
<script type="text/javascript" src="js/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
function doLogin(){
$.ajax({
url:'doLogin',
type:'post', //使用post方法
dataType:'json',//服务器端返回的数据格式是json
data: {
},//发给服务器端的数据
success:function(data){ //data:服务器端返回给浏览器端的数据
if(data.code==0){
alert("登录成功,跳转首页!");
// location.href='index.html';
}else{
alert(data.msg)
}
},
error:function (XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest);
alert(textStatus);
alert(errorThrown);
}
});
}
</script>
说明:
通过jquery实现ajax请求
并且通过
dataType:'json',指明 服务器返回json数据格式
定义返回的 JSON数据格式
前后端程序员,需要事先定义好 JSON 数据格式,这样才能够正常通信
后端 返回给 前端 的 JSON格式,如下:
{
"code":0,
"msg":"success"
}
格式参考:
https://developers.weixin.qq.com/doc/offiaccount/Custom_Menus/Deleting_Custom-Defined_Menu.html
https://ai.baidu.com/ai-doc/FACE/7k37c1ucj#%E8%BF%94%E5%9B%9E%E8%AF%B4%E6%98%8E
后端 JAVA
springboot 使用 jackson库,将 java类对象 转换成 json格式
JsonResult代码
Controller将返回前台的数据封装到 JsonResult 类对象中
一般该类有以下属性:
int code:0表示成功,非0表示失败String msg:提示信息,如:success
完整代码如下:
public class JsonResult {
private int code;
private String msg;
public JsonResult() {
}
public JsonResult(int code, String msg) {
this.code = code;
this.msg = msg;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
Controller
@Controller
public class LoginCtrl {
// @RequestMapping("/doLogin")
@PostMapping("/doLogin")
@ResponseBody
public JsonResult doLogin(){
JsonResult jr=new JsonResult(0,"sucess");
// JsonResult jr=new JsonResult(1,"用户名或密码错误,请重新登录!");
return jr;
}
}
说明:
@ResponseBody:由于是 ajax 发来的请求,并且前台要求服务器返回 json数据格式,所以需要在方法上声明@ResponseBody注解,该注解的作用:springmvc 使用 jackson库,将返回的 java类对象 转换成 json对象JsonResult:将返回给前台的数据,封装到JsonResult类中,源代码见下面
