从嵌套函数中获取变量

时间:2012-11-05 19:26:07

标签: javascript function nested xmlhttprequest

想知道是否有人可以帮助回答我的问题,我需要从“数据”中获取xml内容,因为它是在yam_send函数内的嵌套函数中定义的,我试图使用return将变量返回到函数'GetBasicStatus',但它不是一路走来,任何人都可以对此有所了解。对不起,如果这是一个明显的解决方案,我担心初学者。

function GetBasicStatus()

    {
        //do some stuff & define variable "command"
        data = yam_send(command);

        if (window.DOMParser)
        {
            parser=new DOMParser();
            xmlDoc=parser.parseFromString(data,"text/xml");
        }
        else    // Internet Explorer
        {
            xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
            xmlDoc.async=false;
            xmlDoc.loadXML(data);
        }
    }

    function yam_send(str)
    {

        var xmlhttp;

        if (window.XMLHttpRequest)

        {// code for IE7+, Firefox, Chrome, Opera, Safari

        xmlhttp=new XMLHttpRequest();

        }

    else

        {
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
        }


    xmlhttp.onreadystatechange=function()
    {
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
            var data=xmlhttp.responseText;
            return data;
        }


    }
    xmlhttp.open("GET","test.php?str",true);
    xmlhttp.send();
    }

1 个答案:

答案 0 :(得分:1)

您提供的xmlhttp.onreadystatechange功能是回调功能。它在事件发生时执行,不能向“父”函数返回任何内容。

您可以在父函数中创建一些变量,并在回调中为其指定一些值。或者使用父函数作为回调,如下所示:

var xmlResponse = null; //variable for usage outside of GetBasicStatus
function GetBasicStatus(data) {
    xmlResponse = data; //now you can use it.
    if (window.DOMParser)
    {
        parser=new DOMParser();
        xmlDoc=parser.parseFromString(data,"text/xml");
    }
    else    // Internet Explorer
    {
        xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.async=false;
        xmlDoc.loadXML(data);
    }
}

function yam_send(str)
{
    var xmlhttp;

    if (window.XMLHttpRequest)
        {// code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp=new XMLHttpRequest();
        }
    else
        {
            xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
        }

    xmlhttp.onreadystatechange=function()
        {
            if (xmlhttp.readyState==4 && xmlhttp.status==200)
            {
                var data=xmlhttp.responseText;
                GetBasicStatus(data);
            }
        }
    xmlhttp.open("GET","test.php?str",true);
    xmlhttp.send();
}