【问题标题】:XHR request undefinedXHR 请求未定义
【发布时间】:2012-11-18 03:59:15
【问题描述】:

我有点卡住了,我有两个函数调用填充并使用 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;
?>

什么可能导致问题???

希望您能提供帮助! 谢谢!

【问题讨论】:

  • 有什么理由不使用 JQuery 等 Javascriot 框架?
  • 因为我不想使用 jQuery 或任何框架?
  • call_data 不返回任何内容...
  • 不会是:xmlhttp.onreadystatechange=cfunc; 吗?执行函数
  • 因为他不需要为一个简单的 XHR 导入庞大的框架?

标签: javascript ajax


【解决方案1】:

由于这是异步的(毕竟这就是 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;

【讨论】:

    猜你喜欢
    • 2019-06-18
    • 2018-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-29
    • 1970-01-01
    相关资源
    最近更新 更多