从匿名函数中检索值就绪状态改变

发布于 2024-09-16 01:04:49 字数 1094 浏览 3 评论 0原文

我有一个函数,每当单击按钮时,我希望从中返回一个值作为一系列事件。但是,我不知道如何从 onreadystatechange 检索值。我怎样才能返回vicArray[vicID]

function selectVictim()
{
var vicString;
var vicArray;
var vicID;

var params = "url=queenofsheep.com/Sheep/victims.php";
var request = new ajaxRequest();

request.open("POST", "victims.php", true);
request.setRequestHeader("Content-Type",
                             "application/x-www-form-urlencoded");
request.setRequestHeader("Content-Length", params.length);
request.setRequestHeader("Connection", "close");

request.send(params);

request.onreadystatechange = function ()
{
    if (this.readyState == 4)
    {
        if (this.status == 200)
        {
            if (this.responseText != null )
            {
                vicString = this.responseText;
                vicArray = JSON.parse(vicString);
                vicID = Math.floor(Math.random() * (vicArray.length - 1));
            }
            else alert("Ajax error: No data received");
        }
        else alert("Ajax Error: " + this.statusText);
    }
}
alert(vicArray[vicID]);
}

I have a function from which I would like to return a value as a series of events whenever a button is clicked. However, I can't figure out how to retrieve the value from onreadystatechange. How can I make it so I can return vicArray[vicID]?

function selectVictim()
{
var vicString;
var vicArray;
var vicID;

var params = "url=queenofsheep.com/Sheep/victims.php";
var request = new ajaxRequest();

request.open("POST", "victims.php", true);
request.setRequestHeader("Content-Type",
                             "application/x-www-form-urlencoded");
request.setRequestHeader("Content-Length", params.length);
request.setRequestHeader("Connection", "close");

request.send(params);

request.onreadystatechange = function ()
{
    if (this.readyState == 4)
    {
        if (this.status == 200)
        {
            if (this.responseText != null )
            {
                vicString = this.responseText;
                vicArray = JSON.parse(vicString);
                vicID = Math.floor(Math.random() * (vicArray.length - 1));
            }
            else alert("Ajax error: No data received");
        }
        else alert("Ajax Error: " + this.statusText);
    }
}
alert(vicArray[vicID]);
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

染柒℉ 2024-09-23 01:04:49

你不能。 onreadystatechange 处理程序在selectVictim 函数返回后很长时间内被调用。

可以说,这里的函数是“异步函数”,即不是立即生成返回值,而是在某个异步过程之后生成返回值的函数。

为了解决这个问题,必须使用回调来提供返回值:

function selectVictim( callback )
{
    ...
    ...

    request.onreadystatechange = function() {
        ...
        vicArray[vicID] = ...;
        callback( vicArray[vicID] );
    }
}

请注意 callback 参数。无论谁调用这个函数,都必须为此参数提供另一个函数。然后注意当返回值准备好时 selectVictim 如何调用回调。

现在,无论您在哪里调用 selectVictim,您都必须将代码从: 修改

function someFunc()
{
    doSomething();

    var vic = selectVictim();

    domeSomethingElseWithVictim( vic );
}

为:

function someFunc()
{
    doSomething();

    selectVictim( function( vic ) {

        domeSomethingElseWithVictim( vic );

    } );
}

足够简单吗?

You can't. Your onreadystatechange handler gets called long after the selectVictim function returns.

What you have here is, so to say, "asynchronous functions" - i.e. functions that generate their return value not immediately, but after a certain asynchronous process.

To deal with this, one has to use a callback to provide return value:

function selectVictim( callback )
{
    ...
    ...

    request.onreadystatechange = function() {
        ...
        vicArray[vicID] = ...;
        callback( vicArray[vicID] );
    }
}

Note the callback argument. Whoever calls this function, must provide another function for this argument. Then note how selectVictim calls the callback when the return value is ready.

Now wherever you call selectVictim, you must modify your code from:

function someFunc()
{
    doSomething();

    var vic = selectVictim();

    domeSomethingElseWithVictim( vic );
}

To:

function someFunc()
{
    doSomething();

    selectVictim( function( vic ) {

        domeSomethingElseWithVictim( vic );

    } );
}

Simple enough?

断舍离 2024-09-23 01:04:49

我将使用回调,您可以在其中传递响应准备好后运行的函数。

添加callback 作为参数:

function selectVictim(callback)

然后:

vicString = this.responseText;
vicArray = JSON.parse(vicString);
vicID = Math.floor(Math.random() * (vicArray.length - 1));
if (callback) {
 callback(vicID);
}

当您调用该函数时,您可以执行以下操作:

selectVictim(function(vicID){ 
  console.log('This is the id: ', vicID); 
});

如果您不想直接执行此操作,也可以将该函数作为值传递。注意:如果您发出大量请求并且需要保留发出请求的顺序,这会变得有点棘手,但有一些方法可以处理这个问题。

I would use a callback, in which you can pass the function that runs once the response is ready.

Add callback as a param:

function selectVictim(callback)

and then:

vicString = this.responseText;
vicArray = JSON.parse(vicString);
vicID = Math.floor(Math.random() * (vicArray.length - 1));
if (callback) {
 callback(vicID);
}

When you call the function you could do this:

selectVictim(function(vicID){ 
  console.log('This is the id: ', vicID); 
});

You can also pass the function as a value if you prefer not to do it directly. Note: it gets a little tricky if you make a ton of requests and you need to preserve the order in which they were made, but there are ways to handle that.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文