我正在尝试使用ajax和spring制作你好的世界,但它不起作用,我不知道为什么。
我的servlet是:
import javax.servlet.http.HttpServlet;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class SomeController {
@RequestMapping(value = "/profile", method = RequestMethod.GET)
public @ResponseBody
String processAJAXRequest(
@RequestParam("firstname") String firstname,
@RequestParam("lastname") String lastname) {
String response = "HELLO: " + firstname + " " + lastname;
return response;
}
}
我的ajax页面是:
<html>
<head>
<title>TODO supply a title</title>
<meta charset="windows-1250">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<form id="sampleForm" method="post" action="/profile">
<div>
<input type="text" name="firstname" id="firstname">
</div>
<div>
<input type="text" name="lastname" id="lastname">
</div>
<div>
<button type="submit" name="submit">Submit</button>
</div>
</form>
<script>
$(document).ready(function () {
$('#sampleForm').submit(
function (event) {
var firstname = $('#firstname').val();
var lastname = $('#lastname').val();
var data = 'firstname='
+ encodeURIComponent(firstname)
+ '&lastname='
+ encodeURIComponent(lastname);
$.ajax({
url: $("#sampleForm").attr("action"),
data: data,
type: "GET",
success: function (response) {
alert(response);
},
error: function (xhr, status, error) {
alert(xhr.responseText);
}
});
return false;
});
});
</script>
</body>
</html>
当我尝试发送表单时,我收到error 404
。你能帮助我吗?哪里有问题?
来自extends
的正常servlet HttpServlet
正常工作。