returning xmlhttp responseText from function as return [duplicate]

冷暖自知 提交于 2019-12-03 07:13:49
jAndy

You can't.

Neither runs the code syncronous, nor would you return anything to loadXMLDoc but to the anonymous function which is the onreadystatechange handler.

Your best shot is to pass a callback function.

function loadXMLDoc(myurl, cb){
   var xmlhttp;
   if (window.XMLHttpRequest){
       xmlhttp=new XMLHttpRequest();}
   else{
       xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");}

    xmlhttp.onreadystatechange=function(){
        if (xmlhttp.readyState==4 && xmlhttp.status==200){
            if( typeof cb === 'function' )
                cb(xmlhttp.responseText);
        }
    }

   xmlhttp.open("GET",myurl,true);
   xmlhttp.send();

}

And then call it like

loadXMLDoc('/foobar.php', function(responseText) {
    // do something with the responseText here
});

Just return the responseText property or assign its value to a variable in closure.

Returning a value:

<script>
    function loadXMLDoc(myurl) {
        var xmlhttp;
        if (window.XMLHttpRequest) {
            xmlhttp = new XMLHttpRequest();
        } else {
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }

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

        xmlhttp.open("GET", myurl, true);
        xmlhttp.send();
        return xmlhttp.onreadystatechange();
    }
</script>

Using a closure:

<script>
    var myValue = "",
        loadXMLDoc = function (myurl) {
            var xmlhttp;
            if (window.XMLHttpRequest) {
                xmlhttp = new XMLHttpRequest();
            } else {
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            }

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

            xmlhttp.open("GET", myurl, true);
            xmlhttp.send();
            myValue = xmlhttp.onreadystatechange();
        };
</script>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!