Javascript 将参数传递给 ajax onreadystatechange 回调?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8582663/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 06:34:55  来源:igfitidea点击:

Pass arguments into ajax onreadystatechange callback?

javascriptajax

提问by Brian McFarland

What's the normal pure javascript (i.e. not JQuery) way to pass arguments into an anonymous onreadystatechange callback?

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

For example:

例如:

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.... */
}

回答by George

Javascript supports closures, so the anonymous function you wrote will be able to access xhttpand msgfrom the enclosing doRequest()scope.

Javascript 支持闭包,因此您编写的匿名函数将能够访问xhttpmsg从封闭doRequest()范围。

If wanted to do this explicitly (say, if you want to define the callback function somewhere else in the code and reuse it), you could create a function that creates the callbacks. This also allows you to alias the variables to be accessible with different names (like xand m):

如果想显式地执行此操作(例如,如果您想在代码的其他位置定义回调函数并重用它),您可以创建一个创建回调的函数。这也允许您使用不同的名称(如xm)为变量设置别名:

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

and then in doRequest(), do xhttp.onreadystatechange = createCallback(xhttp, msg);

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

If all you wanted to do was 'rename' the variables, you can do this inline and anonymously:

如果您只想“重命名”变量,您可以内联和匿名执行此操作:

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

回答by vernonner3voltazim

Part of the above answer didn't work for me. First, for a separate callBack function having no parameters:

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

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

Now suppose the callBack function is modified to receive some parameters:

现在假设回调函数被修改为接收一些参数:

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

However, elsewhere here at StackOverflow someone explained that it had to do with the need to assign a "function reference" instead of a "function call" to onreadystatechange (like the NAME above is a function reference), and posted a solution:

然而,在 StackOverflow 的其他地方有人解释说,这与需要为 onreadystatechange 分配“函数引用”而不是“函数调用”有关(就像上面的 NAME 是函数引用一样),并发布了一个解决方案:

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

I came here to add something to that other Answer, but now can't find it. So I might as well add it here. In my own code I was using both local variables and global variables, and discovered something that didn't seem to work right, but now that I know what actually happened, a Word Of Warning seems appropriate. Assume "g" is a global variable:

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

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

The function reference is assigned to onreadystatechange at some point in time (T0), and the callBack function is called called at a different time (T1). Well, the value of global variable "g" at T1 is the value that gets passed to the callBack function, NOT the value of "g" when the function reference was assigned at T0. Don't let this bite you like it bit me! (Local variables generally don't have this problem because they are usually out of scope at T1, so JavaScript has to use their existing values at T0, when setting the parameter-values of the anonymous function.)

在某个时间点 (T0) 将函数引用分配给 onreadystatechange,并在不同时间 (T1) 调用 callBack 函数。好吧,T1 处的全局变量“g”的值是传递给回调函数的值,而不是在 T0 处分配函数引用时“g”的值。不要让这个咬你喜欢它咬我!(局部变量通常没有这个问题,因为它们通常在 T1 超出范围,因此 JavaScript 在设置匿名函数的参数值时必须使用它们在 T0 的现有值。)

回答by Simon Hi

Never too late! :-)

永远不会太晚!:-)

Instead of passing data using arguments in xhttp.onreadystatechange which is somewhat complicated, one can just add properties to the xhr object itself.

无需在 xhttp.onreadystatechange 中使用参数传递数据,这有点复杂,您只需向 xhr 对象本身添加属性即可。

For instance:

例如:

var m = "Hello!";
var xhttp = new XMLHttpRequest();
xhttp.m = m;
xhttp.onreadystatechange = function()
{
    var x, m;
    x = this;
    m = x.m;
    if ((x.readyState == 4) && (x.status == 200))
    {
        alert(m);
    }
};
// ...