javascript - 在ajax调用之外访问数组?
问题描述
全部!我有一个 ajax 调用来获取 API 的结果。当我尝试在调用之外访问该数组时,它是空白的。帮助?
在下面的代码中,我获取属性列表,然后将结果分配给“mlsArray”变量。当我在 main 中控制台记录它时,我得到了想要的结果。
但是,如果我稍后调用 getHomes,则该数组为空。
main(auth) {
$.ajax({async: false,
url: "https://api.simplyrets.com/properties?
limit=500&lastId=0&status=active&maxprice=" +
this.maximum + "&type=residential",
type: 'GET',
dataType: 'json',
// authorize with the API credentials
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", "Basic " + auth);
},
success: function(res) {
this.mlsArray = Object.assign([], res);
console.log(this.mlsArray);
}
});
}
getHomes() {
console.log(this.mlsArray);
}
}
解决方案
您在这里处理的是javascript this
“范围”规则。函数的上下文(默认情况下)采用调用它的对象的上下文(参见:https ://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this )。
当你调用函数success
时,你需要在函数中找到你想要bind
的上下文:
success: function (res) {
// do things ...
}.bind(this)
祝你好运!
推荐阅读
- python-2.7 - 函数格式表示形式识别
- c++ - 如何将用逗号和空格分隔的整数读入二维数组?
- pandas - 我应该如何使用上一行的 fillna 结果填充 na?
- html - 无法向左移动这个 div?
- clojure - 克洛朱尔。使用正则表达式替换具有相同字符数的子字符串
- spring - Spring Oauth2 CORS
- python - 在python中,我试图使用for循环计算列表中的每个元素,但它多次返回元素出现n
- c++ - 如何传递多个 std::filesystem 选项?
- java - JavaFX:如何将图像添加到已用另一种方法初始化的矩形?
- python - 尝试使用正则表达式后,Beautiful Soup 出现错误