button按钮添加单击事件实现ajax请求,设置了$.post在网页上还是显示get请求

<%--
  Created by IntelliJ IDEA.
  User: naruto
  Date: 2022/9/5
  Time: 19:27
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>Title</title>
    <link rel="stylesheet" href="bootstrap-3.4.1-dist/css/bootstrap.css">
</head>
<script src="js/jquery-3.5.1.js"></script>
<script type="text/javascript">

    $(function (){

        $("#btnSub").click(function (){
            $.post(
                "${pageContext.servletContext.contextPath}/loginServlet",
                {account:$("#inputName").val(),password:$("#inputPassword3").val()},
                function (data){
                    $("#msg").text(data);
                }
            )
        })
    })
</script>
<body>
<div class="container">
    <span id="msg"style="color: red"></span>

    <form class="form-horizontal">
        <div class="form-group">
            <label for="inputName" class="col-sm-2 control-label">用户名</label>
            <div class="col-sm-10">
                <input type="text" class="form-control" id="inputName" placeholder="请输入用户名" name="account">
            </div>
        </div>
        <div class="form-group">
            <label for="inputPassword3" class="col-sm-2 control-label">密码</label>
            <div class="col-sm-10">
                <input type="password" class="form-control" id="inputPassword3" placeholder="请输入密码" name="password">
            </div>
        </div>

        <div class="form-group">
            <div class="col-sm-offset-2 col-sm-10">
                <button type="submit" class="btn btn-default" id="btnSub">提交</button>
            </div>
        </div>
    </form>
</div>

</body>
</html>

出现问题 button按钮的type属性 设置为submit时,会刷新页面,无法实现异步请求,将type属性设置为button,这时按下时不会执行任何操作.

 

posted @ 2022-09-06 08:42  传说中的旅行者  阅读(125)  评论(0编辑  收藏  举报