如何在完成提取时调用方法

时间:2017-11-03 14:17:16

标签: ajax ecmascript-6

如何在ajax fetch完成后调用方法?

这是我的代码到目前为止,但回调方法不会找到this.display。

class fourViews {
  static display(data){
  // Some stuff being displayed...
  }
  loadPage(){
   let url = "www.example.com";
   fetch(url).then(function(data) {
     this.display(data);
   }).catch(function(error) {
      // If error.          
   });
  } 
}

1 个答案:

答案 0 :(得分:1)

您的方法display是静态的,因此您不应期望在this上定义它(无论如何这都不是您的对象)。而是使用类名:

fetch(url).then(function(data) {
    fourViews.display(data);
})



class fourViews {
  static display(data){
    console.log('display called:\n', data.body);
  }
  loadPage(){
    let url = "https://jsonplaceholder.typicode.com/posts/1";
    fetch(url).then(function(response) {
        // Note that the response object has methods to return promises to data,
        // like json():
        response.json().then(function (data) {
            fourViews.display(data); // static methods are not called on `this`
        })
    }).catch(function(error) {
      // If error.          
    });
  } 
}

new fourViews().loadPage();




相关问题