在jsp示例中形成ajax数据

时间:2016-06-30 14:45:30

标签: javascript ajax

我想在ajax电话中正确形成 数据 参数。

<script type="text/javascript">
    $(document).ready(function() {
        $('#call').click(function ()
        {
            $.ajax({
                type: "post",
                url: "books", //this is my servlet
                data: <<< my data here >>>
            });
        });

    });
</script>

这是我的jsp

的一部分
<form action="books" method="post">
    <table width="70%" border="1">
        <%
            List<Book> books = (List<Book>) request.getAttribute("books");

            for (int i = 0; i < books.size(); i++) {
        %>
        <tr>

            <td>
                <input type="checkbox" name="book<%=i%>"
                       value="<%= books.get(i).getBook_id()%>"> <%= books.get(i).getName() %>
            </td>

        </tr>
        <%
            }
        %>
    </table>

    <select name="user_name">
        <%
            List<User> users = (List<User>) request.getAttribute("users");
            for (int i = 0; i < users.size(); i++) {
        %>
        <option value="<%=users.get(i).getName()%>"><%=users.get(i).getName()%></option>
        <%
            }
        %>
    </select>
    <input type="submit" name="submit" value="Purchase">
    <input type="button" value="Call Servlet" name="Call Servlet" id="call"/>
</form>

我想通过上面form通常经过的所有内容。 您可以通过此示例向我展示ajax技术吗?

1 个答案:

答案 0 :(得分:1)

为表单提供instance id并使用serialize()方法

       $('#form').submit(function ()
        {
            $.ajax({
                type: "post",
                url: "books", //this is my servlet
                data: $(this).serialize()
            });
        });


    <form id="form" action="books" method="post">
        <table width="70%" border="1">
            <%
                List<Book> books = (List<Book>) request.getAttribute("books");

                for (int i = 0; i < books.size(); i++) {
            %>
            <tr>

                <td>
                    <input type="checkbox" name="book<%=i%>"
                           value="<%= books.get(i).getBook_id()%>"> <%= books.get(i).getName() %>
                </td>

            </tr>
            <%
                }
            %>
        </table>

        <select name="user_name">
            <%
                List<User> users = (List<User>) request.getAttribute("users");
                for (int i = 0; i < users.size(); i++) {
            %>
            <option value="<%=users.get(i).getName()%>"><%=users.get(i).getName()%></option>
            <%
                }
            %>
        </select>
        <input type="submit" name="submit" value="Purchase">
        <input type="button" value="Call Servlet" name="Call Servlet" id="call"/>
    </form>