springboot+jQuery+ajax实现一个简单的输入框的动态检测
1、在idea中新建一个springboot的项目,记得在选择项中勾上springWeb和模板引擎Thymeleaf
2、在resource目录下的templates新建一个index.html文件
代码为如下:
<!DOCTYPE html>
<html lang="en" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context">
<head>
<mvc:annotation-driven enable-matrix-variables="true"/>
<context:component-scan base-package="com.example.demo"/>
<mvc:default-servlet-handler/>
<meta charset="utf-8" />
<title></title>
<script type="text/javascript" src="/js/jquery-3.4.1.min.js"></script>
<script type="text/javascript">
function f() {
$.ajax({
url:"/a",
data:{
"username":$("#yy").val()
},
success:function (data) {
console.log(data);
if(data.toString() == "success")
{
$("#comtext").html("用户名合法")
}else {
$("#comtext").html("用户名不合法")
}
}
})
}
</script>
</head>
<body>
<p>
用户名:
<input id="yy" type="text" onblur="f()">
<span id="comtext"></span>
</p>
</body>
</html>
3、注意由于springboot2.0以上版本会拦截静态资源,所以需要新建一个配置类来添加静态资源加载路径
代码如下:
package com.example.demo.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.*;
@Configuration
public class Config implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**","/js/**").addResourceLocations("classpath:/static/","classpath:/js/");
}
}
4、新建一个controller来响应ajax请求并返回相对应的数据
代码如下:
package com.example.demo.controller;
import com.sun.deploy.net.HttpRequest;
import com.sun.deploy.net.HttpResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.xml.ws.Response;
import java.util.ArrayList;
import java.util.List;
@Controller
public class helloController {
@ResponseBody
@RequestMapping("/a")
public String hello(String username)
{
if(username.equals("ljl"))
{
return "success"; //如果ajax请求过来的参数满足判断条件返回success
}
return "failure"; //如果ajax请求过来的参数不满足判断条件就failure
}
}
5、启动该项目
当鼠标离开输入框时,会发送一个get请求,判断用户名是否合法
当用户名不合法时:
总结
1、在引入jquery时,由于引入的路劲错误,造成页面的请求不到该资源所以你在出现类似的错误的时候,查看一下你的引入的路径是否正确。
2、由于springboot2.0以上版本会对静态资源进行拦截,所以应该新建一个配置类重写addResourceHandlers方法,添加自己的资源路径。