将AJAX调用分配给全局变量

时间:2016-04-28 17:50:24

标签: javascript php ajax

我有一个问题(How to pass variables and data from PHP to JavaScript?)的以下代码:

<!-- snip -->
<script>
    function reqListener () {
      console.log(this.responseText);
    }

    var oReq = new XMLHttpRequest(); //New request object
    oReq.onload = function() {
        //This is where you handle what to do with the response.
        //The actual data is found on this.responseText
        alert(this.responseText); //Will alert: 42
    };
    oReq.open("get", "get-data.php", true);
    //                               ^ Don't block the rest of the execution.
    //                                 Don't wait until the request finishes to 
    //                                 continue.
    oReq.send();
</script>
<!-- snip -->

我需要的是将this.responseText传递给名为“result”的全局变量,如下所示:

<script>
var result;

    var oReq = new XMLHttpRequest();
    oReq.onload = function getData() {
        result = this.responseText;
    };
    oReq.open("get", "data.php", true);
    oReq.send();


    document.write(result);
</script>

代码确实从data.php获取数据,但是我得到一个“提升”问题,关于如何将结果传递给全局变量的任何想法?

1 个答案:

答案 0 :(得分:0)

正如评论中所提到的,它不是一个悬挂问题,问题是您在XHR调用返回数据之前尝试使用result。您只需将引用移至result回调内的oReq.onload即可让当前代码生效:

var result;
var oReq = new XMLHttpRequest();
oReq.onload = function getData() {
    result = this.responseText;
    console.log(result);
};
oReq.open("get", "data.php", true);
oReq.send();

然后只需更新应用程序的任何部分需要数据,而不是将其记录到控制台。