使用AJAX从引导模式更新数据库

时间:2016-01-03 13:24:49

标签: javascript jquery ajax twitter-bootstrap jsp

我正在创建一个显示数据库中某些记录的页面(请参阅屏幕截图)。每行都有一个编辑按钮,可以打开一个引导模式,用于输入注释和更改用户的状态。单击完成按钮后,我必须使用AJAX更新数据库中的更改。然而,它没有正常工作。我似乎无法理解出了什么问题。 Displaying records from database Modal for adding comments and changing status of user

这是我的jsp页面......

    <%@page import="java.sql.ResultSet"%>
    <%@page import="java.sql.Statement"%>
    <%@page import="java.sql.Connection"%>
    <%@page import="java.util.ArrayList"%>

    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"    "http://www.w3.org/TR/html4/loose.dtd">
   <html lang="en">
   <head>
   <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
   <title>Insert title here</title>
   <link rel="stylesheet"
    href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script
    src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script
    src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script type="text/javascript"
    src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<%
    String loginIdEdit = "";
%>



                    **<script>
                        $(function() {
                            //twitter bootstrap script
                            $("button#save").click(function(e) {

                                $.ajax({

                                    type : "POST",
                                    url : "defaulterUpdater.jsp",
                                    data : $('form.contact').serialize(),
                                    success : function(msg) {

                                    },
                                    error : function() {
                                        alert("Failed");
                                    }
                                });
                            });
                        });
                    </script>**

<script type="text/javascript">
    function myFun() {
        alert("welcome");
        var demo = document.createElement('div');
        demo.innerHTML = demo.innerHTML
                + "<tr><input type='text' name='mytext'><tr>";
    }
</script>
</head>
<body>
    <div class="container">
        <form method="post" action="RegistrationServlet">

            <%
                response.setHeader("Cache-Control", "no-cache");
                response.setHeader("Cache-Control", "no-store");
                response.setHeader("Pragma", "no-cache");
                response.setDateHeader("Expires", 0);
                Connection con = null;

                con = DBManager.getConnection();
                Statement st = con.createStatement();

                String userName = "";
                ArrayList<AutoDefaulterVO> defaulterList = null;

                HttpSession session2 = request.getSession();
                if (session2.getAttribute("first_name") == null) {
                    out.println("Your session expired.....");
            %>



            <a href="Home.jsp">Please Login Again to continue</a>
            <%
                } else {
                    defaulterList = (ArrayList<AutoDefaulterVO>) session2
                            .getAttribute("autoDefaulterList");
                    userName = session2.getAttribute("first_name").toString();
            %>

            <form action='LogoutServlet' method=POST>
                <table align="right" style="width: 100%">
                    <tr>
                        <td align="left"><input type="submit" name="logout"
                            value="Home" onclick="form.action='AdminHome';">
                        </td>
                        <td align="right"><input type="submit" name="logout"
                            value="Logout" onclick="form.action='LogoutServlet'">
                        </td>
                    </tr>
                </table>
            </form>



            <h3 align="center">Auto Defaults</h3>
            <table border="1" style="width: 100%">
                <br>
                <br>


                <h3 align="center">
                    Welcome
                    <%=userName%></h3>

                <table border="1" style="width: 100%" class="table table-hover">
                    <tr>
                        <th>Default Status</th>
                        <th>Borrower Name</th>
                        <th>Borrower Rating</th>
                        <th>Accural Status</th>
                        <th>Bank Number</th>
                        <th>Account Number</th>
                        <th>Days Past Due</th>
                        <th>Comments</th>
                    </tr>

                    <%
                        for (int i = 0; i < defaulterList.size(); i++) {
                                AutoDefaulterVO defaulter = new AutoDefaulterVO();
                                defaulter = defaulterList.get(i);
                                loginIdEdit = defaulter.getDefaulterLoginID();
                                System.out.println("Printing only auto defaulter in jsp ");
                    %>
                    <tr>
                        <%-- <td><%=defaulter.getDefaultStatus()%></td> --%>

                        <td>Auto Defaulter</td>
                        <td><%=defaulter.getBorrowerName()%></td>
                        <td><%=defaulter.getBorrowerRating()%></td>
                        <td><%=defaulter.getAccuralStatus()%></td>
                        <td><%=defaulter.getBankNumber()%></td>
                        <td><%=defaulter.getAccountNumber()%></td>
                        <td><%=defaulter.getDaysPastDue()%></td>
                        <%-- <td><%=loginIdEdit%></td> --%>
                        <td>
                            <%
                                ResultSet rs = st
                                                .executeQuery("select * from aip_comments");
                                        while (rs.next()) {
                                            System.out.println("Auto defaulter loginId printing-->"
                                                    + defaulter.getDefaulterLoginID());
                                            String loginId = rs.getString("login_id");
                                            System.out.println("databse loginId printing-->"
                                                    + rs.getString("login_id"));
                                            if (defaulter.getDefaulterLoginID().equals(
                                                    rs.getString("login_id"))) {
                            %> <%=rs.getString("comments")%> <%
    }
            }
 %>
                        </td>
                        <td>
                            <!-- <form name="editForm" action="edit.jsp">
                            <button type="button" data-toggle="modal" class="btn btn-default" data-target="#myModal">Edit</button>

                            -->
                            <form class="contact">


                                <button href="#edit-modal" type="button" data-toggle="modal"
                                    class="btn btn-default" data-target="#<%=loginIdEdit %>">Edit</button>
                                <!-- <a  data-toggle="modal" data-target="#<%=loginIdEdit%>" href="#">Edit</a> -->

                                <!-- <input type="submit" name="editButton" value="Edit"> -->
                                <!--<input type="hidden" id="edit" name="edit" value="<%=loginIdEdit%>" />-->
                        </td>

                        <div class="modal fade" id="<%=loginIdEdit%>" role="dialog">
                            <div class="modal-dialog">
                                <div class="modal-content">
                                    <div class="modal-header">
                                        <button type="button" class="close" data-dismiss="modal">&times;</button>
                                        <h4 class="modal-title">
                                            Edit status and add comment for
                                            <%=defaulter.getBorrowerName()%></h4>
                                    </div>

                                    <div class="modal-body">


                                        <div class="form-group">
                                            <label for="sel1"><span></span>Select status:</label> <select
                                                class="form-control" id="sel1" name="sel1">
                                                <option>Validate Error</option>
                                                <option>Auto Weaver</option>
                                                <option>ReDefault</option>
                                            </select>

                                        </div>
                                        <div class="form-group">
                                            <label for="defaultercomment"><span></span>Add
                                                comment:</label> <input type="text" class="form-control"
                                                name="defaultercomment" id="defaultercomment"<%-- value="<%=loginIdEdit%>" --%>>
                                        </div>
                                    </div>
                                    <div class="modal-footer">
                                        <button type="button" id="save" name="save"
                                            class="btn btn-default" data-dismiss="modal" align="centre">Done</button>
                                    </div>

                                </div>
                            </div>
                        </div>
                        </form>
                        <%
                            }
                        %>
                    </tr>

                </table>




                <%
                    }
                %>

</body>
</html>

ajax URL重定向到jsp页面下面的defaulterUpdater.jsp,我只打印这些值以查看它们是否被正确检索。

    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<% String selection = request.getParameter("sel1");
String comment = request.getParameter("defaultercomment");

System.out.println("selection-"+selection+"comment--"+comment);
%> 


</body>
</html>

仅接受第一行的值。对于其余行,将打印空值。任何帮助将不胜感激。谢谢!

2 个答案:

答案 0 :(得分:0)

你把模态错误放在表格里面。通过表格语法,这是错误的。你必须从表中放出这个模态,并在bootstrap的shown.bs.modal事件中调用ajax。

因为你需要重复按钮。保持按钮的硬连线ID将打开模态,同时保留data-attribute-id以唯一标识单击的按钮,这将帮助您获取有关列表中单击的按钮的详细信息(因为按钮对每行重复,你的data-attribute-id将是行的loginid。

然后用事件shown.bs.modal编写jquery,比如

$("#modalId").on("shown.bs.modal", function(e){
var btnClicked= $(e).relatedTarget();
var btnClickedId= btnClicked.data("attribute-id"); // id of clicked button

// here more code see attached link below for more

}

我之前在asp.net mvc上发布了一个similer回答,但你会有想法,因为情况对你来说是个比喻。 请访问我在问题dynamically created bootstrap3 modals do not work

上的回答

希望有助于解决这个问题。

@Update部分删除了一些代码以获得干净的视图

<script type="text/javascript">

   $(document).ready(function () {
        $('#editModal').on('show.bs.modal', function (event) {
            var button = $(event.relatedTarget);//Button which is clicked
            var clickedButtonId= button.data('loginidedit');//Get loginidedit of the button or get other variable same
          $("#loginid").val(clickedButtonId);//Put here id of the btn clicked which has attribute for loginidedit
    //you can get here other required filed or make ajax call to get other values formt he database for                  this loginidedit.

        })
    });
</script>



<body>
    <div class="container">

//Table here
          <table border="1" style="width: 100%" class="table table-hover"> 
                    <%
                        for (int i = 0; i < defaulterList.size(); i++) {
                                AutoDefaulterVO defaulter = new AutoDefaulterVO();
                                defaulter = defaulterList.get(i);
                                loginIdEdit = defaulter.getDefaulterLoginID();
                                System.out.println("Printing only auto defaulter in jsp ");
                    %>
                    <tr>
                       <td>
                                <button href="#edit-modal" type="button" data-toggle="modal"
                                    class="btn btn-default" data-target="#editModal" data-loginidedit = "<%=loginIdEdit %>">Edit</button> 
                        </td>
                    </tr>
                        <%
                            }
                        %>
                </table>



//Modal here
                        <div class="modal fade" id="editModal" role="dialog">
                            <div class="modal-dialog">
                                <div class="modal-content">
                                    <div class="modal-header">                                     
                                    </div>
                                 <form class="contact"> //give action, method attribute here or make ajax call on save button clicked,

                          <input type="hidden" name="????" id="loginid">// the modal on shown will fill this value.

                                    <div class="modal-body">
                                        <div class="form-group">
                                        <label for="sel1"><span></span>Select status:</label> <select
                                            class="form-control" id="sel1" name="sel1">
                                            <option>Validate Error</option>
                                            <option>Auto Weaver</option>
                                            <option>ReDefault</option>
                                        </select>

                                    </div>
                                    <div class="form-group">
                                        <label for="defaultercomment"><span></span>Add
                                            comment:</label> <input type="text" class="form-control"
                                            name="defaultercomment" id="defaultercomment"<%-- value="<%=loginIdEdit%>" --%>>
                                    </div>
                                    </div>
                                    <div class="modal-footer">
                                        <button type="button" id="save" name="save"
                                            class="btn btn-default" data-dismiss="modal" align="centre">Done</button>
                                    </div>
                                </form>
                                </div>
                            </div>
                        </div>

</body>
</html>



           $(function() {
                            //twitter bootstrap script
                            $("button#save").click(function(e) {

                                $.ajax({

                                    type : "POST",
                                    url : "defaulterUpdater.jsp",
                                    data : $('form.contact').serialize(),
                                    success : function(msg) {

                                    },
                                    error : function() {
                                        alert("Failed");
                                    }
                                });
                            });
                        });

答案 1 :(得分:0)

我让代码正常工作。基本上需要一个唯一的标识符来完成&#34;完成&#34;按钮是javascript的规则。因此它不适用于所有行。 我给表单提供了独特的ID 并通过提交调用onclick方法.. 的onClick =&#34; callAjax(this.form)&#34;

所以现在它正在运作。谢谢大家的帮助!