从函数返回XMLHTTP的responseText作为回报 [英] returning xmlhttp responseText from function as return

查看:278
本文介绍了从函数返回XMLHTTP的responseText作为回报的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

即时通讯新的JavaScript和PHP,我的目标是:从XMLHTTP的responseText返回字符串函数返回value.So我可以使用它的innerText或innerHTML的方法。 html的code:

 <脚本>
函数loadXMLDoc(myurl){
    VAR XMLHTTP;
    如果(window.XMLHtt prequest){
        XMLHTTP =新XMLHtt prequest();}
    其他{
        XMLHTTP =新的ActiveXObject(Microsoft.XMLHTTP);}

     xmlhttp.onreadystatechange =功能(){
         如果(xmlhttp.readyState == 4和&安培; xmlhttp.status == 200){
              xmlhttp.responseText;}
     }

    xmlhttp.open(GET,myurl,真正的);
    xmlhttp.send();
}
< / SCRIPT>
 

解决方案

您不能。

无论是运行在code syncronous,也不会您返回什么 loadXMLDoc 但对匿名函数这是的的onreadystatechange 的处理程序。

您最好的拍摄是通过一个回调函数。

 函数loadXMLDoc(myurl,CB){
   VAR XMLHTTP;
   如果(window.XMLHtt prequest){
       XMLHTTP =新XMLHtt prequest();}
   其他{
       XMLHTTP =新的ActiveXObject(Microsoft.XMLHTTP);}

    xmlhttp.onreadystatechange =功能(){
        如果(xmlhttp.readyState == 4和&安培; xmlhttp.status == 200){
            如果(typeof运算CB ===功能)
                CB(xmlhttp.responseText);
        }
    }

   xmlhttp.open(GET,myurl,真正的);
   xmlhttp.send();

}
 

然后调用它像

  loadXMLDoc(/ foobar.php',函数(responseText的){
    //做一些与这里的responseText
});
 

im new in javascript and php , my goal is :RETURN string from xmlhttp responseText to a function return value.So i can use it with innerText or innerHTML method. the html code :

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

解决方案

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

这篇关于从函数返回XMLHTTP的responseText作为回报的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆