将参数传递给匿名javascript函数

时间:2022-05-31 22:29:41

Consider the code below:

考虑以下代码:

this.usedIds = 0;

this.SendData = function(data)
{
    var id = this.usedIds;
    this.usedIds++;

    this.xmlHttpThing.open("POST", "/Upload.aspx", true);
    this.xmlHttpThing.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

    var currentObject = this;
    this.xmlHttpThing.onreadystatechange = function() { currentObject.UploadComplete(id) };
    this.xmlHttpThing.send(data);
};
this.UploadComplete = function(id)
{
    if (this.xmlHttpThing.readyState == 4)
    {
        //First time id is 0
        //Second time id is 0                 <<<--------- Why??
        //Third time id is 1
        //Fourth time id is 2
        //Fifth time id is 3 ....         

        this.SendData("blabla");
    }
};

Why does the id i pass to the anonymus function get delayed by one call after the first call?

为什么传递给anonymus函数的id会在第一次调用后被一个调用延迟?

Only seems to be this way in Firefox, in IE the UploadComplete receive the ids in the correct order.

在Firefox中似乎只有这种方式,在IE中,UploadComplete以正确的顺序接收ID。

In the second loop i can stop the debugger at the send(data)-line and confirm that the id is actually 1 but when i get to the UploadComplete it turns out to be 0 in that argument :(

在第二个循环中,我可以在send(data)-line处停止调试器并确认id实际上是1但是当我到达UploadComplete时,它在该参数中变为0 :(

EDIT: Found solution: Disable Console-logging in FireBug.

编辑:找到解决方案:在FireBug中禁用控制台日志记录。

2 个解决方案

#1


I had the same problem too in the past. I don't remember exactly what caused it, but I fixed it by moving the increment to the response handler.

我过去也遇到过同样的问题。我不记得是什么导致它,但我通过将增量移动到响应处理程序来修复它。

this.UploadComplete = function(id)
{
    if (this.xmlHttpThing.readyState == 4)
    {      
        this.usedIDs++;
        this.SendData("blabla");
    }
};

Edit: after thinking about it, my case may have been different from yours. Why not increment this.usedIDs when you assign id?

编辑:在考虑之后,我的情况可能与您的情况有所不同。为什么不在分配id时增加this.usedIDs?

var id = this.usedIDs++;

#2


Disabling the Console-logging in Firebug solved the problem!

在Firebug中禁用控制台日志记录解决了这个问题!

#1


I had the same problem too in the past. I don't remember exactly what caused it, but I fixed it by moving the increment to the response handler.

我过去也遇到过同样的问题。我不记得是什么导致它,但我通过将增量移动到响应处理程序来修复它。

this.UploadComplete = function(id)
{
    if (this.xmlHttpThing.readyState == 4)
    {      
        this.usedIDs++;
        this.SendData("blabla");
    }
};

Edit: after thinking about it, my case may have been different from yours. Why not increment this.usedIDs when you assign id?

编辑:在考虑之后,我的情况可能与您的情况有所不同。为什么不在分配id时增加this.usedIDs?

var id = this.usedIDs++;

#2


Disabling the Console-logging in Firebug solved the problem!

在Firebug中禁用控制台日志记录解决了这个问题!