使用Spring MVC的Ajax无法正常工作

use*_*499 2 java ajax jquery jsp spring-mvc

这是我尝试用户的jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!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>Add Users using ajax</title>
        <script src="/Spring3MVC/js/jquery.js"></script>
        <script type="text/javascript">
        function doAjaxPost() {
            // get the form values
            var firstName = $('#firstName').val();
            var lastName = $('#lastName').val();

            $.ajax({
                type: "POST",
                url: "/insert",
                data: "firstName=" + firstName + "&lastName=" + lastName,
                success: function(response) {
                    // we have the response
                    $('#info').html(response);
                    $('#firstName').val('');
                    $('#lastName').val('');
                },
                error: function(e) {
                    alert('Error: ' + e);
                }
            });
        }
        </script>
    </head>
    <body>
        <h1>Add Person</h1>
        <table>
            <tr><td>First Name : </td><td> <input type="text" id="firstName" name="firstName" /><br/></td></tr>
            <tr><td>Last Name : </td><td> <input type="text" id="lastName" name="lastName" /> <br/></td></tr>
            <tr><td colspan="2"><input type="button" value="Add Users" onclick="doAjaxPost()"><br/></td></tr>
            <tr><td colspan="2"><div id="info" style="color: green;"></div></td></tr>
        </table>
        <a href="/SpringMVC/search">Show All Users</a>
    </body>
</html>
Run Code Online (Sandbox Code Playgroud)

这是我的控制器代码

@RequestMapping(value="/insert", method = RequestMethod.POST)
public String insertPerson(ModelMap model, HttpServletRequest request, HttpServletResponse response, @RequestParam("firstName") String firstName, @RequestParam("lastName") String lastName ) {
    personDao.savePerson(firstName,lastName);
    model.addAttribute("nameAdded", firstName+" "+lastName);
    return "personAdded";
}
Run Code Online (Sandbox Code Playgroud)

当我单击"添加用户"按钮时,没有任何反应.任何人都可以帮我解决这个问题吗?

pap*_*pap 6

您正在使用除Ajax帖子之外的任何地方的上下文URL.

应该

url: "/insert",

也许是

url: "/SpringMVC/insert",

甚至更好

url: "<spring:url value='/insert' />",