首页 > 解决方案 > 带数据库的 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 替换此操作

标签: ajaxjsp

解决方案


$("#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)


推荐阅读