开发者

Returning a value from Javascript function

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>


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);
    }
  }
  ...
}


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;
    }
}


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.


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


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>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜