我正在编写一个完全由 AJAX 驱动的浏览器应用程序(我一生中第一次),这意味着:
- 这将是一个留在浏览器中的页面,根据需要加载程序组件
- 浏览器历史记录将是,好吧,没有。
- 页面根本不会刷新
我关心的是我应该如何处理 XMLHttpRequests,因为我主要是 C++ 程序员,被教导当你写这样的语句时
x = new XMLHttpRequest();
你需要delete
之后它。
这个问题完全是关于内存管理的,这个对象是否分配了new
保留在内存中,即使在完成它的“循环”后,readyState == 4或者以某种方式释放,释放,什么?老实说,我不知道什么时候可以释放它,因为创建这些的脚本将位于 HEAD 中并可能整个工作日都坐在那里。我是否应该:
- 创建一个或多个重复使用的 XMLHttpRequest 类型的对象,对应用程序进行编程,使其不需要超过此限制,
- 或者没关系,我可以根据需要分配任意数量的新 XMLHttpRequest?
考虑到我的网页的“框架”将保留,请在您的答案中包括在什么时候删除这些对象以及为什么会删除这些对象(如果会的话)。希望我清楚地说明了这个问题,并感谢您提供有见地的答案。
EDIT:
考虑一个代码(为了简洁起见,我删除了许多检查意外返回值的行)onClick
事件处理程序,创建 XMLHttpRequest 并发送它:
function submitme(){
var p = document.getElementById('p'); //a text field being sent to server
if(typeof p!='undefined' && p!=null){
if(p.value!=""){
//here XMLHttpRequest is created, this function
//returns exactly object of this type or false, when failed
var xhr=createXmlHttpRequestObject();
if(xhr!=false){
xhr.open("POST", "blablabla.php", true);
xhr.onreadystatechange=function(){
if(xhr.readyState==4){
if(xhr.status==200){
//result will be posted in this div below
var adiv = document.getElementById('resultdiv');
//extract the XML retrieved from the server
xmlResponse = xhr.responseXML;
//obtain the document element (the root element) of the XML structure
xmlDocumentElement = xmlResponse.documentElement;
//get the response text
if(typeof adiv !='undefined' && adiv != null){
adiv.innerHTML=xmlDocumentElement.childNodes[0].firstChild.nodeValue;
}
}//end xhr.status
}//end xhr.readyState
};//end xhr.onreadystatechange
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(p.value);
}//end xhr!=false
}//end p.value!=""
}//end typeof p!='undefined'
}//end submitme()
当创建 XMLHttpRequest 对象实例时,如果触发此处理程序,则它会被引用一次xhr
变量直到处理程序完成执行。此时有有多少参考文献到这个对象实例?如果我正确理解您答案中链接的文章,答案应该是none,浏览器只是等待这个请求转向readystate==4
,完成执行onreadystatechange
函数和对象是无法到达的?请确认。