ajax - 带数据库的 AJAX
问题描述
有一个用于记录新航班的 jsp 表单。我需要使用数据库中的 ajax 检查航班号的可用性。我正在尝试编写一个 ajax 请求,但我是 JS 的初学者。
<div class="form-group">
<div class="input-group">
<input type="number" class="form-control" placeholder="Flight number" id="flightNumber" name="flightNumber" required>
<p class="error-input" id="loginError">
<c:if test="${duplicateFlightNumber == true}">
<fmt:message key="validate.sameFlightNumber"/>
</c:if>
</p>
</div>
</div>
<div class="form-group">
<div class="input-group">
<input type="text" class="form-control" placeholder="From city" id="fromCity" name="fromCity" required>
</div>
</div>
<div class="form-group">
<div class="input-group">
<input type="text" class="form-control" placeholder="To city" id="toCity" name="toCity" required>
</div>
</div>
在没有 ajax 的情况下执行此表单的 Servlet:
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Flight flight = new Flight(); flight.setFlightNumber(Integer.valueOf(req.getParameter("flightNumber")));
flight.setFromCity(req.getParameter("fromCity"));
flight.setToCity(req.getParameter("toCity"));
if (!validation.flightNumberUnique(flightNumber)){
req.setAttribute(DUPLICATE_FLIGHT_NUMBER, true);
forward(Constants.Pages.Admin.ADD_FLIGHT_JSP, req, resp);
return;
}
getFlightService().add(flight);
LOGGER.trace("New flight added");
redirectToAction(Constants.ServletPaths.Admin.ADMIN_ALL_FLIGHT_PATH, req, resp);
}
如何用 ajax 替换此操作
解决方案
$("#flightNumber").change(function(){
var flightnumber = $("#flightNumber").val();
//get to and from values
$.post("servletname",{"flightNumber":flightnumber,"fromCity":fromCity,"toCity":toCity}, function(data, status){
//data contains elements that you print on your servlet
$("#loginerror").text("your message to be displayed in error field");
});
});
$(selector).post(URL,data,function(data,status,xhr),dataType) 用于ajax post请求(Jquery)
推荐阅读
- javascript - JS 不等待等待
- c++ - ntdll.dll XX.exe: 0xC0000139: 未找到入口点
- python - 参数中的Python binance非法字符
- linux - 来自管道和 wc -m 的 bash 脚本输入
- pdf - PDF 未在 GitHub 上正确显示
- node.js - Implementing load protection for Fastify Node js
- dax - Power BI如何根据当前材料计算
- cors - 在 NestJs 中是否可以为单个路由启用 CORS?
- c# - 搜索文件内的文本
- node.js - 无法读取 Nodejs 中未定义的属性“拆分”