从函数返回xmlhttp responseText作为返回[重复项]

问题描述 投票:7回答:2

im是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>
javascript ajax xmlhttprequest responsetext
2个回答
10
投票

您不能。

既不同步运行代码,也不对return进行任何操作,但对[处理程序的匿名函数则无用。

您的最佳选择是传递回调函数。

loadXMLDoc

然后称呼它

function loadXMLDoc(myurl, cb) { // Fallback to Microsoft.XMLHTTP if XMLHttpRequest does not exist. var xhr = (window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP")); xhr.onreadystatechange = function() { if (xhr.readyState == 4 && xhr.status == 200) { if (typeof cb === 'function') cb(xhr.responseText); } } xhr.open("GET", myurl, true); xhr.send(); }


4
投票
仅返回responseText属性或将其值分配给闭包中的变量。]​​>

返回值:

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

使用闭包:

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

© www.soinside.com 2019 - 2024. All rights reserved.