标签:out write 绑定 head color tst lib etc create
$.ajax()
、$.get()
和$.post()
$.ajax()
$.ajax({键值对});
$.ajax()
发送异步请求$.get()
:发送get请求
$.get(url, [data], [callback], [type])
$.post()
:发送post请求
$.post(url, [data], [callback], [type])
前端html代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>注册页面</title>
<script src="js/jquery-3.4.1.min.js"></script>
<script>
//页面加载完成后
$(function () {
//给username绑定blur事件(失去焦点)
$("#username").blur(function () {
//获取username文本输入框的值,发送Ajax请求
var username = $(this).val();
//期望服务器响应的数据格式,{"userExsit":true,"msg":"此用户太受欢迎,请更换一个"}
// {"userExsit":false,"msg":"此用户名可用"}
$.get("findUserServlet",{username:username},function (data) {
//判断userExsit的值是否为true,数据在data里
var span = $("#s_username");//获取span,添加提示信息
if (data.userExsit) {
//用户名存在
span.css("color","red");
span.html(data.msg);
}else {
//用户名不存在
span.css("color","green");
span.html(data.msg);
}
},"json");//最后一个参数,指定响应格式 为json
});
});
</script>
</head>
<body>
<form>
<input type="text" id="username" name="username" placeholder="请输入用户名">
<span id="s_username"></span><br>
<input type="password" name="password" placeholder="请输入密码"><br>
<input type="submit" value="注册"><br>
</form>
</body>
</html>
后端FindUserServlet
package servlet;
import com.fasterxml.jackson.databind.ObjectMapper;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;
/**
* @author Dongao
* @create 2020-03-13 21:52
*/
@WebServlet("/findUserServlet")
public class FindUserServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
//指定json格式的响应,这样不用在前端页面指定$get()中指定
response.setContentType("application/json;charset=utf-8");
//获取用户名
String username = request.getParameter("username");
//调用service层判断用户名是否存在
//此处假设
//期望服务器响应的数据格式,{"userExsit":true,"msg":"此用户太受欢迎,请更换一个"}
// {"userExsit":false,"msg":"此用户名可用"}
Map<String,Object> map = new HashMap<String, Object>();
if("tom".equals(username)){
map.put("userExist",true);
map.put("msg","此用户太受欢迎,请更换一个");
}else {
map.put("userExist",false);
map.put("msg","此用户名可用");
}
//将map转为json,并且传递给客户端
//将map转为json
ObjectMapper mapper = new ObjectMapper();
//第一个参数为Writer对象:将obj对象转换为JSON字符串,并将json数据填充到字符输出流
mapper.writeValue(response.getWriter(),map);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
}
标签:out write 绑定 head color tst lib etc create
原文地址:https://www.cnblogs.com/dongao/p/12484366.html