chuanjiabao
V2EX  ›  程序员

问个js的问题。

By chuanjiabao at 2011 年 6 月 29 日 · 6029 次点击
如下js代码,openProgressBar函数通过ajax,定时请求后端服务。
我发现 ie7好用 chrome就不行。

==============================code===============================
interval = null;

function openProgressBar() {
/* generate random progress-id */
uuid = "";
for (i = 0; i < 32; i++) {
uuid += Math.floor(Math.random() * 16).toString(16);
}
/* patch the form-action tag to include the progress-id */
document.getElementById("upload").action="/upload.php?X-Progress-ID=" + uuid;

/* call the progress-updater every 1000ms */
interval = window.setInterval(
function () {
fetch(uuid);
},
1000
);
}

function fetch(uuid) {
req = new XMLHttpRequest();
req.open("GET", "/progress", 1);
req.setRequestHeader("X-Progress-ID", uuid);
req.onreadystatechange = function () {
if (req.readyState == 4) {
if (req.status == 200) {
/* poor-man JSON parser */
var upload = eval(req.responseText);

document.getElementById('tp').innerHTML = upload.state;

/* change the width if the inner progress-bar */
if (upload.state == 'done' || upload.state == 'uploading') {
bar = document.getElementById('progressbar');
w = 400 * upload.received / upload.size;
bar.style.width = w + 'px';
}
/* we are done, stop the interval */
if (upload.state == 'done') {
window.clearTimeout(interval);
}
}
}
}
req.send(null);
}
3 条回复  •  1970-01-01 08:00:00 +08:00
yyfearth
   1
yyfearth  
   2011 年 6 月 29 日
yyfearth
   2
yyfearth  
   2011 年 6 月 29 日
chuanjiabao
   3
chuanjiabao  
OP
   2011 年 6 月 29 日
@yyfearth 3x a lot
我尝试一下。
• 请不要在回答技术问题时复制粘贴 AI 生成的内容
© 2026 V2EX · 30ms · 3.9.8.5