AJAX小案例

1.AJAX技术:

作用:不用更新 整个页面,对部分数据进行操作

 

2.json格式:

作用:浏览器默认显示的数据为一连串的字符串,可读性较差。而json规定格式化显示,如下:

{"state":2,"message":"用户名不存在!","data":null})

 

3.案例

目的:

  • 登陆浏览器提交get请求:http://localhost:8080/AJAX/user/login.do?username=1&password=1,显示json数据
  • 浏览器提交post请求:http://localhost:8080/AJAX/login.html,输入username,password点击提交,验证输入

 

具体步骤:

  • 创建maven项目  
  • 配置spring.xml的
<bean class = "com.pc.User"></bean>
<!--json格式必须注册驱动-->
	<mvc:annotation-driven />
  • 创建controller并添加相应注解:
package com.pc;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.pc.util.JsonResult;

@RestController
@RequestMapping("user")
public class UserController {
	@RequestMapping("login.do")
	public JsonResult login(
	    @RequestParam("username") String username,
	    @RequestParam("password") String password) {
	    Integer state;
	    String message = null;

	    if ("root".equals(username)) {
	        if ("1234".equals(password)) {
	            state = 1;
	        } else {
	            state = 3;
	            message = "密码错误!";
	        }
	    } else {
	        state = 2;
	        message = "用户名不存在!";
	    }

	    JsonResult jsonResult = new JsonResult();
	    jsonResult.setState(state);
	    jsonResult.setMessage(message);
	    return jsonResult;
	}

}

创建html文件,引入jquery框架,实现ajax异步访问:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<form action="login.html" id="form-login">
	<div>
	用户名:<input type="text" name="username" >
	</div>
	<div>
	密 码:
	<input type="text" name="password">
	</div>
	<input type="button" id="btn-login" value="登录" />
	</form>

	<script type="text/javascript" src="./jquery-3.4.1.min.js"></script>
    <script type="text/javascript">
$("#btn-login").click(function(){
    // $.ajax()函数的参数是1个JSON对象
    // url:请求提交到哪里
    // data:需要提交的请求参数
    // type:请求类型
    // dataType:服务器端响应的数据类型,可以是text/xml/json,取值取决于Response Headers中的Content-Type
    // success:服务器端HTTP响应码是2xx时的回调(callback)函数,函数的参数就是服务器端响应的正文结果
    $.ajax({
        "url":"user/login.do",
        "data":$("#form-login").serialize(),
        "type":"post",
        "dataType":"json",
        "success":function(result) {
            if (result.state == 1) {
                alert("登录成功!");
            } else {
                alert(result.message);
            }
        }
    });
});
</script>
</body>
</html>
  • 打开浏览器测试结果:

0

本节结束,欢迎交流讨论~

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值