[英]Ajax with Spring MVC not working
这是我尝试用户的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>
这是我的控制器代码
@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";
}
当我单击“添加用户”按钮时,没有任何反应。 任何人都可以帮我解决这个问题吗?
您正在使用除Ajax帖子之外的任何地方的上下文URL。
应该
url: "/insert",
也许是
url: "/SpringMVC/insert",
甚至更好
url: "<spring:url value='/insert' />",
尝试
data: {firstName: firstName, lastName: lastName},
代替
data: "firstName=" + firstName + "&lastName=" + lastName,
在你的ajax电话中。
在JSP中使用url
for AJAX请求:
url: "insert"
取代:
url: "/insert"
您正在使用指向服务器根目录而不是控制器的绝对URL。
我已经对它进行了测试,它对我的代码工作正常。
这两个页面的绝对URL是什么,如果你在keybourd上点击f12键,你可以跟踪ajax调用并跟踪响应代码,如果它是200,那么你的服务器端代码没问题,现在检查成功函数,否则检查服务器代码和当前404意味着它没有到达服务器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.