javascript - 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 的初学者,对此我深表歉意:(
解决方案
推荐阅读
- dockerfile - 如何使用 Docker 配置 SAP SNC
- android - 等待 Firebase Auth 完成,然后将数据加载到片段
- pandas - 带有烧瓶的熊猫为搜索数组获取 Nonetype
- c# - 将视图模型发送到局部视图时,为什么会出现类型错误 (InvalidOperationException)?
- go - 杜松子酒如何检查参数是否已发布
- java - Gradle 不解析从父 pom 继承的传递依赖
- python - 如何转义单引号或以其他方式达到最终结果?
- python - 有没有办法使用 python 的 rdflib 模块将 SPARQL 查询解析树反向转换为查询字符串?
- python - 了解 bash 脚本
- php - Message.getAllChats 电报机器人