我有一个问题(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获取数据,但是我得到一个“提升”问题,关于如何将结果传递给全局变量的任何想法?
答案 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();
然后只需更新应用程序的任何部分需要数据,而不是将其记录到控制台。