实现效果描述:当用户输入值以后,将鼠标按钮拿开,系统会自动判断该值是否已经输入过并给出提示。
客户端代码:
<!-- 客户端代码实现 -->
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<!-- html关键表单元素设计 -->
<h1>The Ajax Page</h1>
<fieldset>
<legend>Ajax 表单请求</legend>
<form>
<input type="text" name="name" id="nameId" onblur="doCheck()" onfocus="doClear()">
<input type="button" onclick="doGet()" value="save">
</form>
<span id="result"></span>
</fieldset>
<script type="text/javascript">
//检测名字是否已经存在
function doCheck(){
//1.基于dom事件创建XHR对象
const xhr=new XMLHttpRequest();
//2.设置XHR对象监听状态
xhr.onreadystatechange=function(){
if(xhr.readyState==4&&xhr.status==200){
document.getElementById("result").innerHTML=xhr.responseText;
}
};
//3.建立连接
let name=document.forms[0].name.value;
xhr.open("GET",`doCheck?name=${name}`,true);
//4.发送请求
xhr.send(null);
}
/function doClear(){
//表示能向id为result的对象插入“”内容
document.getElementById("result").innerHTML="";
}
function doGet(){
//在此函数中向服务端发起异步请求,检测name是否存在
//1.基于dom事件创建XHR对象
const xhr=new XMLHttpRequest();
//2.设置XHR对象监听状态
xhr.onreadystatechange=function(){
if(xhr.readyState==4&&xhr.status==200){ document.getElementById("result").innerHTML=xhr.responseText;//获取响应数据
}
};
//3.创建与服务端的连接
let name=document.forms[0].name.value;
console.log("name:",name);
xhr.open("GET",`doSave?name=${name}`,true);
//4.发送异步请求实现与服务端的通讯
xhr.send(null);//get请求send方法传值
}
</script>
</body>
</html>
服务端代码:
package com.cy.ajaxcontroller;
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
//这是一个服务端,用来处理客户端的请求
@Controller
@RequestMapping("/")
public class AjaxController {
private List<String> names=new ArrayList<String>();
//假如这是存储数据的表
@RequestMapping("doSave")
@ResponseBody
//将客户端请求的数据name写入到names对应的集合
public String doSave(String name){
System.out.println("name="+name);
names.add(name);
return name+"save ok";
}
@RequestMapping("doCheck")
@ResponseBody
//通过此方法检验名字是否已经存在
public String doCheck(String name) {
if(names.contains(name)) ~~~~
return "名字:"+name+"已经存在,请选择其他名字";
return "名字:"+name+"不存在,可以注册";
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。