首页 > 解决方案 > xttp请求后如何在JavaScript中全局保存变量

问题描述

我想从 php 网页获取 http 响应并将其保存在我的 javascript 代码变量中

这是我的代码:

    let state="";
function ajax(url) {
    return new Promise(function(resolve, reject) {
        var xhr = new XMLHttpRequest();
        xhr.onload = function() {
            resolve(this.responseText);
        };
        xhr.onerror = reject;
        xhr.open('GET', url);
        xhr.send();
    });
}
ajax("./code.php")
    .then(function(result) {
      this.state=result; 
      console.log(this.state)// work correctly
    })
    .catch(function() {
    });

console.log(this.state) //undefinde 

当我在我的保存功能中使用控制台登录时,状态变量正确记录但在功能控制台之外记录了 undefiend

我该如何解决这个问题

我是 javascript 的初学者,对此我深表歉意:(

标签: javascriptecmascript-6

解决方案


推荐阅读