此问题全网唯一!
关于MultiActionController异步请求Ajax,pc端正常,手机端报error问题;此问题一般是通过setInterval,seTimeout,做Ajax轮询时会产生此问题;
其实最主要问题有两个:
1.写 setInterval或seTimeout这个方法时 方法中直接写要运行的函数名,并赋值一个变量,这个变量必须是全局变量;
2. 在ajax中 同步参数这个async必须是false;[ async : false, ],否则pc端游览器正常,手机端游览器报error错误;这个错误并不是数据 格式不对而引起的,而这是因为手机端在轮询调取ajax时 ajax没有同步而造成了互相之间冲突;
下面是一个获取图片上传进度的一段 js 代码图片:
下面是 js 完整代码:
//每100ms获取一次图片上传进度
var intervalId;
function interval() {
intervalId = window.setInterval(showPercent, 100)
}
//获取图片进度数据
function showPercent() {
$.ajax( {
type : "POST",
contentType : false,
async : false,
cache : false,
url : "intoNetTCSubmit.htm?method=selectUploadPercent",
dataType : "json",
success : function(data) {
console.log(data);
var end = 0;
var per = 0;
end = data[0].end;
per = data[0].percent + "%"
console.log(per);
console.log("end:" + end);
$("#percent").val(data[0].percent);//图片上传进度
$("#sum").html(data[0].sum == 0 ? 1 : data[0].sum);//第几张图片
$("#per").html(per);
if (end == '-1') { //图片上传结束标识
stopInterval();
//图片上传完成session重置
clearPercent();
}
},
error : function(data) {
console.log(data);
stopInterval();
clearPercent();
alert("ajax异常!!!");
}
});
}
//清除进度数据
function clearPercent() {
$.ajax( {
type : "POST",
contentType : false,
async : false,
cache : false,
url : "intoNetTCSubmit.htm?method=clearUploadPercent",
dataType : "json",
success : function(data) {
console.log("ddd:"+data);
},
});
}
//清除setInterval
function stopInterval() {
window.clearInterval(intervalId);
}
java 代码:
public ModelAndView selectUploadPercent(HttpServletRequest request,HttpServletResponse response){
System.out.println("方法进入controller");
HttpSession session = request.getSession();
int percent = session.getAttribute("upload_percent") == null ? 0: Integer.parseInt(session.getAttribute("upload_percent").toString());
int sum = session.getAttribute("upload_sum") == null ? 0: Integer.parseInt(session.getAttribute("upload_sum").toString());
int end = session.getAttribute("upload_end") == null ? 0: Integer.parseInt(session.getAttribute("upload_end").toString());
String jsonStr = "{percent:'+percent+',sum:'+sum+',end:'+end+'}";
Map<String, Integer> map = new HashMap<String, Integer>();
try
{
map.put("percent",percent);
map.put("sum",sum);
map.put("end",end);
JSONArray json1 = JSONArray.fromObject(map);
//将json数据返回
response.getWriter().write(json1.toString());
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
//数据复原
public void clearUploadPercent(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
HttpSession session = request.getSession();
session.setAttribute("upload_percent",0);
session.setAttribute("upload_sum",1);
session.setAttribute("upload_end",0);
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("percent",0);
map.put("sum", 0);
map.put("end", 0);
JSONArray json1 = JSONArray.fromObject(map);
response.getWriter().write(json1.toString());
}