jqury的ajax

时间:2023-03-10 04:27:19
jqury的ajax

前端代码:

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!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=UTF-8">
<script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery-1.8.3.js"></script>
<script type="text/javascript">
function checkIn(){
var val=$("#listAllEmp").val();//#必须带上
console.log(val)
$.ajax({
url:'${pageContext.request.contextPath }/checkInOut/checkIn.do',//传入的路径+key
type:'GET',//使用get请求,如果用post,值写在data里
data:{val:val},//option的值传入后台
dataType:'text',//返回的数据类型,就是后台返回回来的类型,可以是html,或xml
async:true,//使用异步方式
success:function(data){//成功后返回值data
alert(data)
},
error:function(){//失败的处理
},
});
} </script>
<title>签到签退</title>
</head>
<body>
<select id="listAllEmp" name="listAllEmp">
<option value="1">--------请选择-------</option>
<c:forEach items="${employees}" var="emp">
<option value="${emp.id }">
${emp.name}
</option>
</c:forEach>
</select>
<button id="checkIn" name="checkIn" onclick="checkIn()">签到</button>
</body>
</html>

后端代码

package com.bike.servlet;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping; import com.bike.domain.Employee;
import com.bike.service.EmpTimeService; @Controller
@RequestMapping("/checkInOut")
public class CheckInOutController {
//先展示所有员工
@Resource
EmpTimeService empTimeService;
public void setEmpTimeService(EmpTimeService empTimeService) {
this.empTimeService = empTimeService;
} @RequestMapping("/listAllEmp")
public String listAllEmp(Model model) {
System.out.println("执行1");
List<Employee> employees=empTimeService.listAllEmp();
model.addAttribute("employees", employees);
return "checkInOut";
} }

最好加上@RequestParam(value="val",required=false)