从函数返回xmlhttp responseText作为return

ino*_*box 7 javascript ajax xmlhttprequest responsetext

我是javascript和php的新手,我的目标是:从xmlhttp responseText返回字符串到函数返回值.所以我可以将它与innerText或innerHTML方法一起使用.HTML代码:

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

    xmlhttp.open("GET",myurl,true);
    xmlhttp.send();
}
</script>
Run Code Online (Sandbox Code Playgroud)

jAn*_*ndy 10

你不能.

既没有运行代码同步,也没有return任何东西,loadXMLDoc只有匿名函数是onreadystatechange处理程序.

你最好的方法是通过一个回调函数.

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();

}
Run Code Online (Sandbox Code Playgroud)

然后称之为

loadXMLDoc('/foobar.php', function(responseText) {
    // do something with the responseText here
});
Run Code Online (Sandbox Code Playgroud)


aus*_*ney 4

只需返回responseText属性或将其值分配给闭包中的变量即可。

返回一个值:

<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>
Run Code Online (Sandbox Code Playgroud)

使用闭包:

<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>
Run Code Online (Sandbox Code Playgroud)

  • 你确实必须对 ajax 使用同步模式(`.open(..., false)`),否则 `return` 是假的。请在此处查看您的代码:http://jsfiddle.net/HApG3/。 (2认同)