简体   繁体   English

在ajax调用之外访问数组?

[英]Accessing an array outside an ajax call?

all! 所有! I have an ajax call grabbing the results of an API. 我有一个ajax调用来获取API的结果。 When I try to access that array outside the call, it's blank. 当我尝试在调用之外访问该数组时,它为空。 Help? 救命?

In the code below, I get the list of properties, then assign the results to the "mlsArray" variable. 在下面的代码中,我获得了属性列表,然后将结果分配给“ mlsArray”变量。 When I console log it inside main, I get the desired result. 当我在main中控制台记录它时,我得到了预期的结果。

However, if I later call getHomes, the array is empty. 但是,如果以后再调用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);
 }
}

What you're dealing with here is javascript this "scoping" rules. 什么你在这里处理是JavaScript的this “作用域”规则。 The context of a function ( by default ) takes on the context of the object that invokes it ( see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this ). 函数的上下文(默认情况下)采用调用它的对象的上下文(请参阅: https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this )。

When you're invoking the function success , you need to bind the context to the one you want inside the function: 调用函数success ,需要bind上下文bind到函数内部所需的上下文:

success: function (res) {
 // do things ...
}.bind(this)

Good luck! 祝好运!

the this here refers to the ajax object . 是指ajax 对象

this.mlsArray  = Object.assign([], res);

wherein the this here below refers to the window object which has all the global properties and methods. 其中下面的this是指具有所有全局属性和方法的窗口对象。

getHomes() {
  console.log(this.mlsArray);
 }

1.Either bind the values to the window object by using 1.使用以下方法将值绑定到窗口对象

success: function (res) {
 this.mlsArray  = Object.assign([], res);
 console.log(this.mlsArray);
}.bind(this)

or 要么

  1. make mlsArray as a global variable and refrain from using this keyword. 使mlsArray成为全局变量,并避免使用关键字。

    success: function (res) { mlsArray = Object.assign([], res); 成功:函数(res){mlsArray = Object.assign([],res); console.log(mlsArray); console.log(mlsArray); } }

and in getHomes like below 并在下面的getHomes中

getHomes() {
  console.log(mlsArray);
 }

您应该将ajax调用的success部分中的值分配给全局变量,以便即使在main()函数外部也可以访问它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM