1、在add.html页面绑定键盘按键松开事情onkeyup
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="style/index.css">
<script src="script/axios.min.js"></script>
<script src="script/add.js"></script>
<script src="script/common.js"></script>
</head>
<body>
<div id="div0">
<div id="div_title">
<p>添加水果库存信息</p>
</div>
<div id="div_fruit_table">
<table id="fruit_tbl">
<tr>
<th class="w25">名称:</th>
<td><input type="text" id="fname" onkeyup="checkFname(this.value)"/><span id="fnameSpan"> </span></td>
</tr>
<tr>
<th class="w25">单价:</th>
<td><input type="text" name="price" id="price"/> </td>
</tr>
<tr>
<th class="w25">库存:</th>
<td><input type="text" name="fcount" id="fcount"/> </td>
</tr>
<tr>
<th class="w25">备注:</th>
<td><input type="text" name="remark" id="remark"/> </td>
</tr>
<tr>
<th colspan="2">
<input type="button" value="添加" onclick="add()"/>
<input type="button" value="取消"/>
</th>
</tr>
</table>
</div>
</div>
</body>
</html>
2、在add.js中添加checkFname函数
2.1、common.js
function $(key){
if(key){
if(key.startsWith("#")){
key = key.substring(1)
return document.getElementById(key)
}else{
let nodeList = document.getElementsByName(key)
return Array.from(nodeList)
}
}
}
function add(){
let fname = $("#fname").value
let price = $("#price").value
let fcount = $("#fcount").value
let remark = $("#remark").value
//let fruit = {"fname":fname,"price":price,"fcount":fcount,"remark":remark}
let fruit = {}
fruit.fname=fname
fruit.price = price
fruit.fcount=fcount
fruit.remark=remark
axios({
method:'post',
url:'add',
data:fruit
}).then(response=>{
if(response.data.flag){
window.location.href='index.html'
}
})
}
function checkFname(fname){
axios({
method:'get',
url:"getFname",
params:{
fname:fname
}
}).then(response=>{
let fnameSpan= $("#fnameSpan");
if(response.data.flag){
fnameSpan.innerText = '名称可添加'
fnameSpan.style.color='green'
}else{
fnameSpan.innerText = '名称已存在'
fnameSpan.style.color='red'
}
})
}
3、编写Controller层GetFanemServlet
package com.csdn.fruit.servlet;
import com.csdn.fruit.dao.FruitDao;
import com.csdn.fruit.dao.impl.FruitDaoImpl;
import com.csdn.fruit.dto.Result;
import com.csdn.fruit.pojo.Fruit;
import com.csdn.fruit.util.ResponseUtil;
import jakarta.servlet.GenericServlet;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.annotation.WebServlet;
import java.io.IOException;
@WebServlet("/getFname")
public class GetFnameServlet extends GenericServlet {
FruitDao fruitDao = new FruitDaoImpl();
@Override
public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
String fname = servletRequest.getParameter("fname");
Fruit fruit = fruitDao.getFruitByFname(fname);
ResponseUtil.print(servletResponse, fruit == null ? Result.OK() : Result.Fail());
}
}
![](https://i-blog.csdnimg.cn/blog_migrate/980c4d12019a236ebbc5e6a5488afa1a.png)