2011-12-20 189 views
20

将参数传递给匿名onreadystatechange回调的正常纯javascript(即非JQuery)方式是什么?将参数传递给ajax onreadystatechange回调?

例如:

function doRequest(){ 
    /* Get an XMLHttpRequest in a platform independent way */  
    var xhttp = getXmlHttpRequestObject(); 

    var msg="show this message when done"; /* another variable to pass into callback */ 

    /* How do I pass 'msg' and 'xhttp' into this anonymous function as locals 
     named 'x' and 'm'??? */ 
    xhttp.onreadychangestate=function(x,m) 
    { 
     if(x.readyState == 4) 
     { 
      alert(m); 
     } 
    } 
    /* do the open() and send() calls here.... */ 
} 

回答

31

的JavaScript支持关闭,所以你写的匿名函数就可以从封闭doRequest()范围内访问xhttpmsg

如果想明确地做到这一点(比如说,如果你想在代码的其他地方定义回调函数并重用它),你可以创建一个函数来创建回调函数。这也可以让你别名变量与不同的名称(如xm)访问:

function createCallback(x, m) { 
    return function() { 
     /* Do whatever */ 
    }; 
} 

,然后在doRequest(),做xhttp.onreadystatechange = createCallback(xhttp, msg);

如果你想要做的一切都是“重命名”的变量,你可以这样做内联和匿名:

xhttp.onreadystatechange = (function(x, m) { 
    return function() { 
     /* Do stuff */ 
    } 
})(xhttp, msg); 
+1

谢谢。这个答案促使我学习了更多关于Javascript的知识。我真正需要知道的是关闭是如何工作的。 – 2011-12-21 15:17:44

+0

http.onreadystatechange = function(){ var xmlHttp = this; if(xmlHttp.status == 200)console.log(“We got it!”); } }; – Abbas 2018-01-25 09:09:23

12

上述答案的一部分没有为我工作。首先,对于一个单独的回调函数没有参数:

xhttp.onreadystatechange = callBack; //works; the function's NAME is required 

现在假设回调函数进行了修改,以获得一定的参数:

xhttp.onreadystatechange = callBack(x,m); //didn't work, and didn't know why 
xhttp.onreadystatechange = createCallback(xhttp,msg); //bad part of above Answer 

然而,其他地方在这里StackOverflow的人解释说,不得不做与需要分配一个“功能参考”而不是“函数调用”到的onreadystatechange(像上面的NAME是一个函数引用),并张贴的溶液:

xhttp.onreadystatechange = function(){callBack(x,m);}; //works 

我来这里添加了一些其他的答案,但现在找不到它。所以我不妨在这里添加它。在我自己的代码中,我使用了局部变量和全局变量,并发现了一些似乎并不正确的东西,但现在我知道实际发生了什么,一个警告字似乎是合适的。假设的“g”是一个全局变量:

xhttp.onreadystatechange = function(){callBack(x,g);};//anonymous function works 

功能引用被分配在某个时间点(T 0)至onreadystatechange的,并且回调函数在不同的时间(T1)称为调用。那么,T1处的全局变量“g”的值是传递给回调函数的值,而不是在T0处分配函数引用时的“g”的值。不要让这个咬你一口咬我! (局部变量通常不存在这个问题,因为它们通常在T1的范围之外,所以当设置匿名函数的参数值时,JavaScript必须在T0使用它们现有的值。)