[英]JavaScript, anonymous vs direct function call
在以下代碼段中,我將匿名函數分配給onreadystatechange變量,並且一切正常,但是如果我給該變量分配一個命名函數,它將無法正常工作。
<script language="Javascript">
function postRequest(strURL)
{
var xmlHttp;
if (window.XMLHttpRequest) // Mozilla, Safari, ...
var xmlHttp = new XMLHttpRequest();
else if (window.ActiveXObject) // IE
var xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
xmlHttp.open('POST', strURL, true);
xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlHttp.onreadystatechange = function()
{
alert("you are in anonymous");
}
xmlHttp.send(strURL);
}
</script>
上面的代碼有效,但下面的無效。 函數foo()
不會被調用:
<script language="Javascript">
function foo()
{
alert("you are in foo");
}
/*----------------------------------------------*/
function postRequest(strURL)
{
var xmlHttp;
if (window.XMLHttpRequest) // Mozilla, Safari, ...
var xmlHttp = new XMLHttpRequest();
else if (window.ActiveXObject) // IE
var xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
xmlHttp.open('POST', strURL, true);
xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlHttp.onreadystatechange = foo;
xmlHttp.send(strURL);
}
</script>
這是為什么?
問題已解決。 var xmlHttp必須是全局的。 盡管我沒有在foo()中使用xmlHttp ,但是xmlHttp對象可能在內部需要它! 有人知道為什么嗎? 無論如何,這個問題已為我解決。 謝謝
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.