从 Javascript 函数返回一个值

发布于 2024-11-29 08:36:54 字数 973 浏览 1 评论 0原文

我使用以下代码来显示函数 test2 返回的值。

输出显示为:x 的值是:未定义

任何人都可以帮我解释如何从函数 test2 返回值吗?请注意,函数 test2XMLHTTPRequest

<script language="javascript">

    function test1()
    {
        var x = test2();
        alert('Value of x is: '+x);
    }

    function test2()
    {
        if(window.XMLHttpRequest)
        {
            abcd= new XMLHttpRequest();
        }
        else
        {
            abcd=new ActiveXObject("Microsoft.XMLHTTP");
        }

        abcd.onreadystatechange=function()
        {
            if (abcd.readyState==4 && abcd.status==200)
            {
                    return abcd.responseText; // it is getting value 2 here
            }
            else if(abcd.readyState < 4)
            {
                return -1;
            }
        }
        abcd.open("GET",sam.php,true);
        abcd.send();
    }

</script>

I am using the following code to show value return by the function test2.

The output showing is: Value of x is: undefined

Can anyone help me in explaining how can I return a value from function test2? Please note that the function test2 is XMLHTTPRequest

<script language="javascript">

    function test1()
    {
        var x = test2();
        alert('Value of x is: '+x);
    }

    function test2()
    {
        if(window.XMLHttpRequest)
        {
            abcd= new XMLHttpRequest();
        }
        else
        {
            abcd=new ActiveXObject("Microsoft.XMLHTTP");
        }

        abcd.onreadystatechange=function()
        {
            if (abcd.readyState==4 && abcd.status==200)
            {
                    return abcd.responseText; // it is getting value 2 here
            }
            else if(abcd.readyState < 4)
            {
                return -1;
            }
        }
        abcd.open("GET",sam.php,true);
        abcd.send();
    }

</script>

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

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

发布评论

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

评论(5

梦里梦着梦中梦 2024-12-06 08:36:54

听起来您希望 XML HTTP 请求的值是 test2 的返回值。这是不可能的,因为此 XML HTTP 请求是异步执行的,而 test2 是同步执行的。

处理此问题的正确方法是将回调传递给 test2 以在请求完成时执行。向回调提供从 XML HTTP 请求返回的值。例如

function test1() {
  test2(function (x) {
    alert('The value of x is ' + x);
  });
}

function test2(callback) {
  ...
  abcd.onreadystatechange=function() {
    if (abcd.readyState==4 && abcd.status==200) {
      callback(abcd.responseText);
    } else {
      callback(-1);
    }
  }
  ...
}

It sounds like you want the value from the XML HTTP request to be the return of test2. This is simply not possible as this XML HTTP request executes asynchronously and test2 executes synchronously.

The proper way to handle this is to pass a callback to test2 to execute at the completion of the request. The callback is provided the value which is returned from the XML HTTP request. For example

function test1() {
  test2(function (x) {
    alert('The value of x is ' + x);
  });
}

function test2(callback) {
  ...
  abcd.onreadystatechange=function() {
    if (abcd.readyState==4 && abcd.status==200) {
      callback(abcd.responseText);
    } else {
      callback(-1);
    }
  }
  ...
}
小耗子 2024-12-06 08:36:54

函数test2立即返回(值undefined)。在尝试从中获取任何数据之前,您需要等待 AJAX 调用返回。这是 AJAX 的 (A) 同步部分。

abcd.onreadystatechange=function()
{
    if (abcd.readyState==4 && abcd.status==200)
    {
        // Put the code that deals with the returned value here...
    }
    else if(abcd.readyState < 4)
    {
        return -1;
    }
}

The function test2 returns immediately (the value undefined). You need to wait for your AJAX call to return before you try to get any data from it. That's the (A)synchronous part of AJAX.

abcd.onreadystatechange=function()
{
    if (abcd.readyState==4 && abcd.status==200)
    {
        // Put the code that deals with the returned value here...
    }
    else if(abcd.readyState < 4)
    {
        return -1;
    }
}
一城柳絮吹成雪 2024-12-06 08:36:54

正如预期的那样,函数 test1 调用 test2,从而生成 XMLHttpRequest。但这里的问题是你的时机。 onreadystatechange仅在状态改变时被调用。当状态改变时,函数 test2 已经退出并且没有返回值。

相反,您的警报应该发生在您当前返回 abcd.responseText 的位置。

As expected, the function test1 calls test2, which makes the XMLHttpRequest. But the problem here is with your timing. The onreadystatechange is called only when the state changes. By the time the state changes, the function test2 has already exited without a return value.

Instead, your alert should happen where you currently have return abcd.responseText.

一身软味 2024-12-06 08:36:54

函数 test2 不返回任何内容,而是返回您分配给 onreadystate Change 的回调。您应该从此回调中调用 test1 并将 x 的值传递给它,如下所示:

function test1(x)
{
    alert("X is: " + x);
}

function test2()
{
    // ...
    abcd.onreadystatechange=function()
    {
        var x = -1;
        if (abcd.readyState==4 && abcd.status==200)
        {
                x = abcd.responseText; // it is getting value 2 here
        }
        test1(x); // call test1 and pass in x
    }
    / ...
}

The function test2 is not returning anything but the callback you assigned to onreadystate change is. You should call test1 from this callback and pass the value of x into it like so:

function test1(x)
{
    alert("X is: " + x);
}

function test2()
{
    // ...
    abcd.onreadystatechange=function()
    {
        var x = -1;
        if (abcd.readyState==4 && abcd.status==200)
        {
                x = abcd.responseText; // it is getting value 2 here
        }
        test1(x); // call test1 and pass in x
    }
    / ...
}
零時差 2024-12-06 08:36:54

你不能那样做,你的ajax请求是异步的。因此,当您执行 test2() 时,您不会获得任何值。

请注意,定义 onreadystate 函数时,它会从服务器获取各种响应,这就是为什么您要验证 readystate 4statuscode 200,您将多次进入该函数。当服务器完成时,如果一切顺利,它会返回这些代码。

你应该这样做:

<script language="javascript">

    function test1()
    {
        var x = test2();       
    }

    function test2()
    {
        if(window.XMLHttpRequest)
        {
            abcd= new XMLHttpRequest();
        }
        else
        {
            abcd=new ActiveXObject("Microsoft.XMLHTTP");
        }

        abcd.onreadystatechange= test2Result;
        abcd.open("GET",sam.php,true);
        abcd.send();
    }

    function test2Result()
    {
            if (abcd.readyState==4)
            {
                 if(abcd.status==200)
                 {
                    alert(abcd.responseText); // it is getting value 2 here
                 }
                 else 
                 {
                    alert('Something failed');
                 }
            } 

    }

</script>

You cannot do it that way, your ajax request is asynchronus. So when you are executing test2() you are not getting any value.

Be aware that defining a onreadystate function, it gets various responses from server, thats why you are validating the readystate 4 and statuscode 200, you will get into that function various times. When the server finish it returns those codes if everything went fine.

You should do it like this way:

<script language="javascript">

    function test1()
    {
        var x = test2();       
    }

    function test2()
    {
        if(window.XMLHttpRequest)
        {
            abcd= new XMLHttpRequest();
        }
        else
        {
            abcd=new ActiveXObject("Microsoft.XMLHTTP");
        }

        abcd.onreadystatechange= test2Result;
        abcd.open("GET",sam.php,true);
        abcd.send();
    }

    function test2Result()
    {
            if (abcd.readyState==4)
            {
                 if(abcd.status==200)
                 {
                    alert(abcd.responseText); // it is getting value 2 here
                 }
                 else 
                 {
                    alert('Something failed');
                 }
            } 

    }

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