Kit*_*tet 6 javascript ajax xmlhttprequest
我正在编写一个完全由AJAX驱动的浏览器应用程序(我生命中的第一次),这意味着:
我担心的是我应该怎么做XMLHttpRequests,因为我主要是C++程序员,当你写一个像
x = new XMLHttpRequest();
Run Code Online (Sandbox Code Playgroud)
之后你需要delete
它.
这个问题完全是关于内存管理的,无论这个对象是否new
在内存中分配,即使它在readyState == 4完成它的"循环"之后,或者以某种方式释放,释放,whatchacallit?老实说,我不知道它可以在什么时候被释放,因为创建这些的脚本将在HEAD并且可能整个工作日坐在那里.我是否应该:
考虑到我的网页的"框架"将保留,请在什么时候包括您的答案以及为什么要删除这些对象,如果他们愿意的话.希望我明白这个问题,并感谢任何有见地的答案.
编辑:
考虑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()
Run Code Online (Sandbox Code Playgroud)
创建XMLHttpRequest对象实例时,如果触发此处理程序,则会xhr
一直按变量引用它,直到处理程序完成执行.此时有多少引用此对象实例?如果我理解你的答案正确链接的文章,答案应该是无,浏览器只是等待这个请求转readystate==4
,完成执行onreadystatechange
功能和对象无法访问?请确认.
我最近遇到了同样的问题,我发现互联网上我不应该有任何问题,因为它是垃圾收集.好吧,你应该有顾虑,因为如果你第一次使用它,很容易留下一些参考.
看这个页面:
http://javascript.info/tutorial/memory-leaks
并向下滚动到"XmlHttpRequest ..."
基本上说的是:
如果每次都创建一个新的xhr对象(不要重用它们)并在相应的onreadystatechange回调的闭包中捕获每个xhr对象那么 xhr对象将永远不会被垃圾收集,并且内存泄漏将会增加.
要避免这种情况,请使用this来访问xhr对象(例如,检查状态),并从闭包中获取xhr.