0

我有点卡住了,我有两个函数调用填充并使用 JSON.parse 返回结果。但是当我 console.log 结果我得到“未定义”。

这是我处理请求的函数:

function caller(url,cfunc){
        if (window.XMLHttpRequest)
          {// code for IE7+, Firefox, Chrome, Opera, Safari
                xmlhttp=new XMLHttpRequest();
          }
        else
          {// code for IE6, IE5
                xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
          }
                xmlhttp.onreadystatechange=cfunc;
                xmlhttp.open("GET",url,true);
                xmlhttp.send();
}
function call_data(url,data){
    caller(url,function(){
        if (xmlhttp.readyState==4 && xmlhttp.status==200){
            return( JSON.parse (xmlhttp.responseText) );
        }
    });                                           
}   

电话在这里:

result = call_data('./chk_login.php',0);
console.log(result);

根据 Chrome,我得到的 xhr 请求非常好,并显示了输出。但是 console.log 显示 undefined... 所以你知道这也是我的 PHP 脚本:

<?
    $var = 1;
    echo json_encode($var);
    exit;
?>

什么可能导致问题?

希望你能帮忙!谢谢!

4

1 回答 1

2

由于这是异步的(毕竟这就是 AJAX 中的 A 所代表的意思),所以您不能简单地return期望它会神奇地返回。相反,在回调中操作数据(您已经完成了 80% 的工作)。

function call_data(url,data){
    caller(url,function(){
        if (xmlhttp.readyState==4 && xmlhttp.status==200){
            console.log( JSON.parse (xmlhttp.responseText) );
            ajaxResult = JSON.parse (xmlhttp.responseText);
        }
    });
}

var ajaxResult;
于 2012-11-18T04:12:34.670 回答