【发布时间】:2009-04-16 08:48:24
【问题描述】:
我有一个简单的 Ajax 函数,如下所示:
var x;
var myRequest = new Array();
function CreateXmlHttpReq(handler) {
var xmlhttp = null;
try {
xmlhttp = new XMLHttpRequest();
} catch (e) {
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
}
xmlhttp.onreadystatechange = handler;
return xmlhttp;
}
function getResults() {
var r = Math.random();
var someVar = document.getElementById("myvar").value;
var myUrl = "url/of/my/phpScript.php?";
myUrl += "r=" + r;
//encodeURIComponent() instead of escape() when i aspect normal text
myUrl += "&someVar=" + escape(someVar);
//startLoading just show an overlay with a small rotating gif
startLoading();
x++;
myRequest[x] = CreateXmlHttpReq(function () {
printResultHandler(x);
});
myRequest[x].open("GET", myUrl);
myRequest[x].send(null);
}
//example handler
function printResultHandler(x) {
if (myRequest[x].readyState == 4 && myRequest[x].status == 200) {
//usually i use innerHTML for quick requests, the DOM for more complex req
document.getElementById(div).innerHTML = myRequest[x].responseText;
//this will hide the overlay showed ith startLoading()
stopLoading();
}
}
而且效果很好。当返回流量很大时(它可以是 XML、HTML 或其他),我只是遇到了一些问题,浏览器似乎“睡着了”一段时间。我不喜欢将大量文本(XML、HTML)合二为一。 处理这个不好。
我想知道是否有某种方法可以缓冲该请求。当请求完成并返回200 状态时,有没有办法逐段获取 responseText(比如说 2048 字节或逐行)?
我想是这样的:
function printResultHandler(x) {
if (myRequest[x].readyState == 4 && myRequest[x].status == 200) {
//usually i use innerHTML for quick requests, the DOM for more complex req
//document.getElementById(div).innerHTML = myRequest[x].responseText;
var answer;
while ((answer = readline(myRequest[x].responseText))) {
//to something;
}
//this will hide the overlay showed ith startLoading()
stopLoading();
}
}
简而言之,相当于PHP的readdir()或fread()。
【问题讨论】:
标签: php javascript ajax