使用获取API发布到服务器

时间:2018-10-09 02:15:17

标签: javascript fetch progressive-web-apps

im试图在我的服务器上将帖子的收藏夹状态更改为truefalse,但是我一直反复遇到同样的问题。我单击收藏夹按钮,并确定收藏夹状态已更改。但是当我再次点击它时,什么也没有发生。然后,如果我删除静态缓存并单击“收藏夹”按钮,它的确会更改收藏夹状态,但这只是第一次。基本上每次我需要更改状态时,我都必须删除缓存。当我尝试向服务器添加评论时,发生了同样的事情。这是我向服务器添加收藏夹的代码

static setFavorite() {
      const id = self.restaurant.id;
      const fav_state = self.restaurant.is_favorite;
      const fav_div = document.getElementById('fav_div');
      let image = document.getElementById('fav_img');
      console.log("fav", fav_state);

      if (fav_state == 'true') {
    DBHelper.toggleFavorite(id, false);
    } else {
      DBHelper.toggleFavorite(id, true);
    }
  }

  static toggleFavorite(id, value) {
    fetch('http://localhost:1337/restaurants/' + id + '/?is_favorite=' + value,
      {
        method: 'POST',
        headers: {
            "Content-Type": "application/json; charset=utf-8",
        },
        value: JSON.stringify(value)
      })
    .then(r => r.json())
      .then(res => console.log(value));
  }

1 个答案:

答案 0 :(得分:0)

这里缺少一些代码。看起来setFavorite()函数从fat_state中获取self.restaurant.is_favorite并将该值传递给toggleFavorite。但是您提供的代码中没有任何内容显示如何修改self.restaurant.is_favorite

我不确定在您的代码中是否忘记将其从true切换到false以及从false切换到true

还附带说明(为了在代码中提供更好的JavaScript) 不要使用== true,并且可能尝试重构代码以进行严格的比较(=== true),以避免产生任何副作用。 同样也不确定为什么您的代码以及您提供的与图片相关的代码中根本不需要let image