一、原生Ajax 和SpringMVC 交互
JSP:
<script type="text/javascript" > //因为是原生Ajax是原生javascript代码,不用导入 jquery包
function show_1(){
var CustomerId = $("#lev1").val(); //1、从id为lev1的标签处获取其value值
alert("回来数据了:"+CustomerId);
$.ajax({
url:'showCustomer', // 提交 showCustomer 请求
type:'post',
data:{'id':CustomerId}, // 请求的参数数据
dataType:'json',
success:function(data){ //响应成功之后 返回的数据data ,进行遍历输出
for(var i=0;i<data.length;i++){
alert("回来数据了:"+ data[i].name);
}
}
})
}
</script>
<body>
<select id="lev1" onchange="show_1()" > // 该下拉选择框的值被选中改变后,执行show_1()
<option value="">--请选择--</option>
<c:forEach items="${Customers}" var="Customer">
<option value="${Customer.name}">${Customer.From}</option>
</c:forEach>
</select>
</body>
SpringMVC
@Controller
public class CustomerController2 {
@Autowired CustomerService customerService;
@RequestMapping("Customer") //跳转到该页面的请求,将请求的数据显示在下拉选择框中
public String show(Model model){
List<Customer> ts1 = customerService.showcustomer();
// 设置数据模型返回
model.addAttribute("Customers", ts1);
return "Customer";
}
@RequestMapping("showCustomer") // Ajax 提交了showCustomer 请求,会调控该Controller,返回的是实体类列表集合 List<Customer> ts1,由于@ResponseBody的作用返回的是json 类型
@ResponseBody
public List<Customer> showlev2(@RequestParam(value = "id") int CustomerId){
List<Customer> ts1 = customerService.showLev2ById(CustomerId);
return ts1;
}
}
一、jquery 封装的 Ajax 和SpringMVC 交互
JSP
<script type="text/javascript" src="static/js/jquery.min.js"></script> //因为是jquery 封装的Ajax,需要导入 jquery包
<script type="text/javascript" >
$(function() {
$("#lev1").change(function() { //1。定位到找到id为lev1的元素,一旦里面的值发生了改变执行下面函数体(jquery封装方式)
var CustomerId = $(this).val(); // 写$("#lev1").val();也可以
alert("回来数据了111:"+CustomerId);
$.post( "showTask2",{"id":CustomerId} ,function(data,status){ // 2、post方式提交 Ajax请求,格式:$.post( url,请求参数 ,请求成功后的回调函数(返回的数据处理)){}(jquery封装的方式:)
$.each(data, function(index, element) { // 3、循环显示数据(jquery封装的方式 )
alert("回来数据了:"+element.name);
});
} );
});
});
</script>
<body>
<select id="lev1" >
<option value="">--请选择--</option>
<c:forEach items="${Customers}" var="Customer">
<option value="${Customer.name}">${Customer.From}</option>
</c:forEach>
</select>
</body>
SpringMVC
@Controller
public class CustomerController2 {
@Autowired CustomerService customerService;
@RequestMapping("Customer") //跳转到该页面的请求,将请求的数据显示在下拉选择框中
public String show(Model model){
List<Customer> ts1 = customerService.showcustomer();
// 设置数据模型返回
model.addAttribute("Customers", ts1);
return "Customer";
}
@RequestMapping("showCustomer") // Ajax 提交了showCustomer 请求,会调控该Controller,返回的是实体类列表集合 List<Customer> ts1,由于@ResponseBody的作用返回的是json 类型
@ResponseBody
public List<Customer> showlev2(@RequestParam(value = "id") int CustomerId){
List<Customer> ts1 = customerService.showLev2ById(CustomerId);
return ts1;
}
}
参考:
https://www.cnblogs.com/xiaoxi/p/5708084.html
https://blog.csdn.net/Song_JiangTao/article/details/82697819
https://blog.csdn.net/zahngjialiang/article/details/77899365