实际上。我遇到了从我的Jsp到我的Spring MVC控制器的第一个ajax调用。我从互联网上获得了这个例子,http://maxheapsize.com/2010/07/20/spring-3-mvc-ajax-and-jquery-magic-or-better-simplicity/
Ajax javascript函数为:
<script type="text/javascript" src="scripts/jquery.js"></script>
<script type="text/javascript">
function doAjax() {
$.ajax({
url: 'time.html',
data: ({name : "me"}),
success: function(data) {
$('#time').html(data);
}
});
}
</script>
HTML as:
<button id="demo" onclick="doAjax()" title="Button">Get the time!</button>
<div id="time">
</div>
和MVC控制器:
package com.maxheapsize.springmvc3.controller;
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;
import org.springframework.web.servlet.ModelAndView;
import java.util.Date;
@Controller
public class HelloWorldController {
@RequestMapping("/hello")
public ModelAndView helloWorld() {
return new ModelAndView("hello", "message", "Spring MVC Demo");
}
@RequestMapping(value = "/time", method = RequestMethod.GET)
public @ResponseBody String getTime(@RequestParam String name) {
String result = "Time for " + name + " is " + new Date().toString();
return result;
}
}
从MVC控制器,您可以看到请求映射是“/ time”。通常,如果我们从JSP调用控制器,我们只需要调用/ time来访问控制器,但我不明白,为什么我必须从Ajax url:function调用'time.html'?有什么不同?为什么?
请有人向我解释一下!