weixin_33696106 2018-11-15 09:20 采纳率: 0%
浏览 60

AJAX与数据库

There is a jsp form for recording a new flight. I need to check the availability of the flight number using ajax in the database. I'm trying to write an ajax request, but I'm beginner in 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>

Servlet that proceed this form without ajax:

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);
}

How can I replace this manipulation with ajax

  • 写回答

1条回答 默认 最新

  • 10.24 2018-11-15 11:02
    关注
    $("#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) is used for ajax post request (Jquery)

    评论

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效