html
<button onclick="del()">批量删除</button>
js
<script type="text/javascript">
//批量删除
function del(){
$.ajax({
type: 'POST',
url: "http://localhost:8080/ModelTest1/test/del",
dataType: 'json',
success:function(json){
//开启轮询
c = window.setInterval("getResult('http://localhost:8080/ModelTest1/test/cheak',"+json.no+")",1000); //间隔多少秒去触发ajax
}
});
}
//轮询ajax
function getResult(url,no){
$.ajax({
type:'post',
url:url,
dataType:'json',
async: true,
data:{
'no':no
},
success:function(json){
if(json.type==1){
alert("批量删除已完成")
//关闭轮询
window.clearInterval(c);
}
}
});
}
</script>
java 控制层
@Controller
@RequestMapping("/test")
public class Test {
/**
* 批量删除
* @return
* @throws IOException
*/
@ResponseBody
@RequestMapping(value = "del", method = RequestMethod.POST)
public String del(HttpServletRequest request) throws IOException {
Map map = new HashMap();
String no = System.currentTimeMillis()+"";
HttpSession session = request.getSession();
//通过添加一条session来模拟添加数据库,把no传给前端,前端轮询通过no来查询是否已完成
session.setAttribute(no,false);
//开线程处理数据,把参数no传给线程,线程处理完后修改状态为已完成,因为不是数据库,所以要把session也传过去
ThreadDel threadDel = new ThreadDel(no,session);
Thread thread = new Thread(threadDel);
thread.start();
//把no返回给前端
map.put("no", no);
return JSON.toJSONString(map);
}
/**
* 通过no查询批量删除是否已完成
* @return
* @throws IOException
*/
@ResponseBody
@RequestMapping(value = "cheak", method = RequestMethod.POST)
public String cheak(String no,HttpServletRequest request) throws IOException {
Map map = new HashMap();
//通过查询session模拟查询数据库
boolean isSussion = (boolean)request.getSession().getAttribute(no);
System.out.println(isSussion);
//判断是否已处理完成
if(isSussion == true){
map.put("type", 1);
map.put("msg", "批量删除已完成!");
}else{
map.put("type", 0);
map.put("msg", "正在删除数据中......");
}
return JSON.toJSONString(map);
}
}
java 线程类(通过线程处理数据)
public class ThreadDel extends Thread{
private String no;
private HttpSession session;
@Override
public void run() {
try {
//通过休眠模拟处理数据消耗的时间
Thread.sleep(6000);
//处理成功修改状态(如果是数据库则需要查询后修改)
session.setAttribute(no,true);
}catch (Exception e){
e.printStackTrace();
}
}
public ThreadDel(String no,HttpSession session) {
this.no = no;
this.session = session;
}
}